<commit_before>/*
 * Copyright (C) 2014 INRA
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *    1. Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *    2. Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef __Benchmark_models_hpp__
#define __Benchmark_models_hpp__

#include "linpackc.hpp"
#include "defs.hpp"
#include <vle/mpi-synchronous.hpp>
#include <vle/utils.hpp>
#include <fstream>
#include <numeric>

namespace bench {

struct TopPixel : AtomicModel
{
    int m_id;
    std::string m_name;
    long int m_duration;

    TopPixel(const vle::Context& ctx)
        : AtomicModel(ctx, {}, {"0"})
    {}

    virtual ~TopPixel()
    {}

    virtual double init(const vle::Common& common, const double&) override final
    {
        try {
            m_id = boost::any_cast <int>(common.at("id"));
            m_name = std::string("top-") + boost::any_cast <std::string>(common.at("name"));
            m_duration = boost::any_cast <long int>(common.at("duration"));
        } catch (const std::exception &e) {
            throw std::invalid_argument("TopPixel: failed to find name "
                                        "or duration parameters");
        }

        return 0.0;
    }

    virtual double delta(const double&) override final
    {
        if (m_duration > 0)
            bench::sleep_and_work(m_duration);

        return 1.0;
    }

    virtual void lambda() const override final
    {
        vle_dbg(AtomicModel::ctx, "[%s] lambda\n", m_name.c_str());

        y[0] = {m_id};
    }
};

struct NormalPixel : AtomicModel
{
    enum Phase { WAIT, SEND };

    int          m_id;
    std::string  m_name;
    double       m_current_time;
    double       m_last_time;
    long int     m_duration;
    unsigned int m_neighbour_number;
    unsigned int m_received;
    unsigned int m_total_received;
    Phase        m_phase;
    double       m_simulation_duration;

    NormalPixel(const vle::Context& ctx)
        : AtomicModel(ctx, {"0"}, {"0"})
        , m_current_time(Infinity <double>::negative)
        , m_last_time(Infinity <double>::negative)
        , m_neighbour_number(0)
        , m_received(0)
        , m_total_received(0)
        , m_phase(WAIT)
    {
        try {
            m_simulation_duration = boost::any_cast <double>(ctx->get_user_data());
        } catch (const std::exception &e) {
            throw std::invalid_argument("Normal pixel can not read the "
                                        "simulation duration parameter");
        }
    }

    virtual ~NormalPixel()
    {
        if (m_total_received != (m_simulation_duration * m_neighbour_number)) {
            vle_dbg(AtomicModel::ctx, "/!\\ [%s] failure: have received %"
                    PRIuMAX " messages (%" PRIuMAX " expected)\n",
                    m_name.c_str(),
                    static_cast <std::uintmax_t>(m_total_received),
                    static_cast <std::uintmax_t>(m_neighbour_number * 10));

#ifdef NDEBUG
            throw std::runtime_error("Bad end\n");
#endif
        }
    }

    virtual double init(const vle::Common& common,
                        const double& t) override final
    {
        m_current_time = t;
        m_last_time = Infinity <double>::negative;

        try {
            m_id = boost::any_cast <int>(common.at("id"));
            m_duration = boost::any_cast <long int>(common.at("duration"));
            m_name = std::string("normal-") +
                boost::any_cast <std::string>(common.at("name"));
            m_neighbour_number =
                boost::any_cast <unsigned int>(common.at("neighbour_number"));
        } catch (const std::exception &e) {
            throw std::invalid_argument("NormalPixel: failed to find duration,"
                                        "name or neighbour_number parameters");
        }

        m_received = 0;
        m_total_received = 0;
        m_phase = WAIT;

        return Infinity <double>::positive;
    }

    virtual double delta(const double& time) override final
    {
        m_current_time += time;

        if (x.empty())
            dint(m_current_time);
        else
            dext(m_current_time);

        if (m_phase == WAIT)
            return Infinity <double>::positive;

        return 0.0;
    }

    void dint(const double& time)
    {
        vle_dbg(AtomicModel::ctx, "[%s] dint at %f\n", m_name.c_str(), time);

        if (m_duration > 0)
            bench::sleep_and_work(m_duration);

        if (m_phase == SEND) {
            vle_dbg(AtomicModel::ctx, "[%s] %" PRIuMAX "-%" PRIuMAX
                    " (neighbour_number : %" PRIuMAX " expected)\n",
                    m_name.c_str(),
                    static_cast <std::uintmax_t>(m_received),
                    static_cast <std::uintmax_t>(m_total_received),
                    static_cast <std::uintmax_t>(m_neighbour_number *
                                                 m_simulation_duration));

            m_phase = WAIT;
            m_total_received += m_received;
            m_received = 0;
            m_last_time = time;
        }
    }

    void dext(const double& time)
    {
        vle_dbg(AtomicModel::ctx, "[%s] dext at %f (x[0].size: %" PRIuMAX " received: %" PRIuMAX " neighbour_number: %" PRIuMAX ")\n",
                m_name.c_str(), time,
                static_cast <std::uintmax_t>(x[0].size()),
                static_cast <std::uintmax_t>(m_received),
                static_cast <std::uintmax_t>(m_neighbour_number));
        if (m_last_time == time) {
            vle_dbg(AtomicModel::ctx, "/!\\ [%s] oups at %f", m_name.c_str(), time);
            throw std::runtime_error("Oups event\n");
        }

        for (size_t i = 0, e = x[0].size(); i != e; ++i)
            vle_dbg(AtomicModel::ctx, "value: %d\n", x[0][i]);

        m_received += x[0].size();

        if (m_received == m_neighbour_number)
            m_phase = SEND;
    }

    virtual void lambda() const override final
    {
        if (m_phase == SEND) {
            vle_dbg(AtomicModel::ctx, "[%s] lambda\n", m_name.c_str());

            y[0] = {m_id};
        }
    }
};

template <typename T>
struct Coupled : T
{
    std::string m_name;

    Coupled(const vle::Context& ctx)
        : T(ctx)
    {}

    Coupled(const vle::Context& ctx, unsigned thread_number)
        : T(ctx, thread_number)
    {}

    virtual ~Coupled()
    {}

    virtual void apply_common(const vle::Common& common) override
    {
        m_name = vle::common_get <std::string>(common, "name");
    }

    virtual vle::Common update_common(const vle::Common& common,
                                      const typename Coupled::vertices& v,
                                      const typename Coupled::edges& e,
                                      int child) override
    {
       auto mdl = v[child].get();

        unsigned int nb = std::accumulate(
            e.cbegin(), e.cend(),
            0u, [&mdl](unsigned int x, const typename Coupled::edges::value_type& edge)
            {
                return edge.second.first == mdl ? x + 1u : x;
            });

        vle::Common ret(common);

        vle_dbg(T::ctx, "[%s] init %s (%p) with %" PRIuMAX " neightbour\n",
                m_name.c_str(),
                vle::stringf("%s-%d", m_name.c_str(), child).c_str(),
                mdl,
                static_cast <std::uintmax_t>(nb));

        ret["id"] = child;
        ret["name"] = vle::stringf("%s-%d", m_name.c_str(), child);
        ret["neighbour_number"] = nb;

        return std::move(ret);
    }
};

template <typename T>
struct RootMPI : T
{
    boost::mpi::communicator com;

    RootMPI(const vle::Context& ctx)
        : T(ctx)
        , com()
    {}

    virtual ~RootMPI()
    {}

    virtual vle::Common update_common(const vle::Common& common,
                                      const typename RootMPI::vertices& v,
                                      const typename RootMPI::edges& e,
                                      int child) override
    {
        (void)v;
        (void)e;

        if (com.size() <= child + 1)
            throw std::invalid_argument("MPI size < children size");

        bench::SynchronousProxyModel* mdl =
            dynamic_cast
            <bench::SynchronousProxyModel*>(T::m_children[child].get());

        if (!mdl)
            throw std::invalid_argument("RootMPI without SynchronousProxyModel");

        mdl->rank = child + 1;

        vle_info(T::ctx, "RootMPI assign %d to child %d\n", mdl->rank, child);

        vle::Common ret(common);

        return std::move(ret);
    }
};

template <typename T>
struct Root : T
{
    Root(const vle::Context& ctx, unsigned thread_number)
        : T(ctx, thread_number)
    {}

    virtual ~Root()
    {}

    virtual vle::Common update_common(const vle::Common& common,
                                      const typename Root::vertices& v,
                                      const typename Root::edges& e,
                                      int child) override
    {
        vle::Common ret(common);

        auto mdl = v[child].get();
        unsigned int nb = std::accumulate(
            e.cbegin(), e.cend(),
            0u, [&mdl](unsigned int x, const typename Root::edges::value_type& edge)
            {
                return edge.second.first == mdl ? x + 1u : x;
            });

        ret["id"] = child;
        ret["name"] = vle::stringf("S%d", child);
        ret["neighbour_number"] = nb;
        ret["tgf-filesource"] = vle::stringf("S%d.tgf", child);
        ret["tgf-format"] = (int)1;

        return std::move(ret);
    }
};

using RootThread = Root <GenericCoupledModelThread>;
using RootMono = Root <GenericCoupledModelMono>;
using RootMPIThread = RootMPI <GenericCoupledModelThread>;
using RootMPIMono = RootMPI <GenericCoupledModelMono>;
using CoupledThread = Coupled <GenericCoupledModelThread>;
using CoupledMono = Coupled <GenericCoupledModelMono>;

}

#endif
<commit_msg>models: throw exception without NDEBUG<commit_after>/*
 * Copyright (C) 2014 INRA
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *    1. Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *    2. Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef __Benchmark_models_hpp__
#define __Benchmark_models_hpp__

#include "linpackc.hpp"
#include "defs.hpp"
#include <vle/mpi-synchronous.hpp>
#include <vle/utils.hpp>
#include <fstream>
#include <numeric>

namespace bench {

struct TopPixel : AtomicModel
{
    int m_id;
    std::string m_name;
    long int m_duration;

    TopPixel(const vle::Context& ctx)
        : AtomicModel(ctx, {}, {"0"})
    {}

    virtual ~TopPixel()
    {}

    virtual double init(const vle::Common& common, const double&) override final
    {
        try {
            m_id = boost::any_cast <int>(common.at("id"));
            m_name = std::string("top-") + boost::any_cast <std::string>(common.at("name"));
            m_duration = boost::any_cast <long int>(common.at("duration"));
        } catch (const std::exception &e) {
            throw std::invalid_argument("TopPixel: failed to find name "
                                        "or duration parameters");
        }

        return 0.0;
    }

    virtual double delta(const double&) override final
    {
        if (m_duration > 0)
            bench::sleep_and_work(m_duration);

        return 1.0;
    }

    virtual void lambda() const override final
    {
        vle_dbg(AtomicModel::ctx, "[%s] lambda\n", m_name.c_str());

        y[0] = {m_id};
    }
};

struct NormalPixel : AtomicModel
{
    enum Phase { WAIT, SEND };

    int          m_id;
    std::string  m_name;
    double       m_current_time;
    double       m_last_time;
    long int     m_duration;
    unsigned int m_neighbour_number;
    unsigned int m_received;
    unsigned int m_total_received;
    Phase        m_phase;
    double       m_simulation_duration;

    NormalPixel(const vle::Context& ctx)
        : AtomicModel(ctx, {"0"}, {"0"})
        , m_current_time(Infinity <double>::negative)
        , m_last_time(Infinity <double>::negative)
        , m_neighbour_number(0)
        , m_received(0)
        , m_total_received(0)
        , m_phase(WAIT)
    {
        try {
            m_simulation_duration = boost::any_cast <double>(ctx->get_user_data());
        } catch (const std::exception &e) {
            throw std::invalid_argument("Normal pixel can not read the "
                                        "simulation duration parameter");
        }
    }

    virtual ~NormalPixel()
    {
        if (m_total_received != (m_simulation_duration * m_neighbour_number)) {
            vle_dbg(AtomicModel::ctx, "/!\\ [%s] failure: have received %"
                    PRIuMAX " messages (%" PRIuMAX " expected)\n",
                    m_name.c_str(),
                    static_cast <std::uintmax_t>(m_total_received),
                    static_cast <std::uintmax_t>(m_neighbour_number * 10));

//#ifdef NDEBUG
            throw std::runtime_error("Bad end\n");
//#endif
        }
    }

    virtual double init(const vle::Common& common,
                        const double& t) override final
    {
        m_current_time = t;
        m_last_time = Infinity <double>::negative;

        try {
            m_id = boost::any_cast <int>(common.at("id"));
            m_duration = boost::any_cast <long int>(common.at("duration"));
            m_name = std::string("normal-") +
                boost::any_cast <std::string>(common.at("name"));
            m_neighbour_number =
                boost::any_cast <unsigned int>(common.at("neighbour_number"));
        } catch (const std::exception &e) {
            throw std::invalid_argument("NormalPixel: failed to find duration,"
                                        "name or neighbour_number parameters");
        }

        m_received = 0;
        m_total_received = 0;
        m_phase = WAIT;

        return Infinity <double>::positive;
    }

    virtual double delta(const double& time) override final
    {
        m_current_time += time;

        if (x.empty())
            dint(m_current_time);
        else
            dext(m_current_time);

        if (m_phase == WAIT)
            return Infinity <double>::positive;

        return 0.0;
    }

    void dint(const double& time)
    {
        vle_dbg(AtomicModel::ctx, "[%s] dint at %f\n", m_name.c_str(), time);

        if (m_duration > 0)
            bench::sleep_and_work(m_duration);

        if (m_phase == SEND) {
            vle_dbg(AtomicModel::ctx, "[%s] %" PRIuMAX "-%" PRIuMAX
                    " (neighbour_number : %" PRIuMAX " expected)\n",
                    m_name.c_str(),
                    static_cast <std::uintmax_t>(m_received),
                    static_cast <std::uintmax_t>(m_total_received),
                    static_cast <std::uintmax_t>(m_neighbour_number *
                                                 m_simulation_duration));

            m_phase = WAIT;
            m_total_received += m_received;
            m_received = 0;
            m_last_time = time;
        }
    }

    void dext(const double& time)
    {
        vle_dbg(AtomicModel::ctx, "[%s] dext at %f (x[0].size: %" PRIuMAX " received: %" PRIuMAX " neighbour_number: %" PRIuMAX ")\n",
                m_name.c_str(), time,
                static_cast <std::uintmax_t>(x[0].size()),
                static_cast <std::uintmax_t>(m_received),
                static_cast <std::uintmax_t>(m_neighbour_number));
        if (m_last_time == time) {
            vle_dbg(AtomicModel::ctx, "/!\\ [%s] oups at %f", m_name.c_str(), time);
            throw std::runtime_error("Oups event\n");
        }

        for (size_t i = 0, e = x[0].size(); i != e; ++i)
            vle_dbg(AtomicModel::ctx, "value: %d\n", x[0][i]);

        m_received += x[0].size();

        if (m_received == m_neighbour_number)
            m_phase = SEND;
    }

    virtual void lambda() const override final
    {
        if (m_phase == SEND) {
            vle_dbg(AtomicModel::ctx, "[%s] lambda\n", m_name.c_str());

            y[0] = {m_id};
        }
    }
};

template <typename T>
struct Coupled : T
{
    std::string m_name;

    Coupled(const vle::Context& ctx)
        : T(ctx)
    {}

    Coupled(const vle::Context& ctx, unsigned thread_number)
        : T(ctx, thread_number)
    {}

    virtual ~Coupled()
    {}

    virtual void apply_common(const vle::Common& common) override
    {
        m_name = vle::common_get <std::string>(common, "name");
    }

    virtual vle::Common update_common(const vle::Common& common,
                                      const typename Coupled::vertices& v,
                                      const typename Coupled::edges& e,
                                      int child) override
    {
       auto mdl = v[child].get();

        unsigned int nb = std::accumulate(
            e.cbegin(), e.cend(),
            0u, [&mdl](unsigned int x, const typename Coupled::edges::value_type& edge)
            {
                return edge.second.first == mdl ? x + 1u : x;
            });

        vle::Common ret(common);

        vle_dbg(T::ctx, "[%s] init %s (%p) with %" PRIuMAX " neightbour\n",
                m_name.c_str(),
                vle::stringf("%s-%d", m_name.c_str(), child).c_str(),
                mdl,
                static_cast <std::uintmax_t>(nb));

        ret["id"] = child;
        ret["name"] = vle::stringf("%s-%d", m_name.c_str(), child);
        ret["neighbour_number"] = nb;

        return std::move(ret);
    }
};

template <typename T>
struct RootMPI : T
{
    boost::mpi::communicator com;

    RootMPI(const vle::Context& ctx)
        : T(ctx)
        , com()
    {}

    virtual ~RootMPI()
    {}

    virtual vle::Common update_common(const vle::Common& common,
                                      const typename RootMPI::vertices& v,
                                      const typename RootMPI::edges& e,
                                      int child) override
    {
        (void)v;
        (void)e;

        if (com.size() <= child + 1)
            throw std::invalid_argument("MPI size < children size");

        bench::SynchronousProxyModel* mdl =
            dynamic_cast
            <bench::SynchronousProxyModel*>(T::m_children[child].get());

        if (!mdl)
            throw std::invalid_argument("RootMPI without SynchronousProxyModel");

        mdl->rank = child + 1;

        vle_info(T::ctx, "RootMPI assign %d to child %d\n", mdl->rank, child);

        vle::Common ret(common);

        return std::move(ret);
    }
};

template <typename T>
struct Root : T
{
    Root(const vle::Context& ctx, unsigned thread_number)
        : T(ctx, thread_number)
    {}

    virtual ~Root()
    {}

    virtual vle::Common update_common(const vle::Common& common,
                                      const typename Root::vertices& v,
                                      const typename Root::edges& e,
                                      int child) override
    {
        vle::Common ret(common);

        auto mdl = v[child].get();
        unsigned int nb = std::accumulate(
            e.cbegin(), e.cend(),
            0u, [&mdl](unsigned int x, const typename Root::edges::value_type& edge)
            {
                return edge.second.first == mdl ? x + 1u : x;
            });

        ret["id"] = child;
        ret["name"] = vle::stringf("S%d", child);
        ret["neighbour_number"] = nb;
        ret["tgf-filesource"] = vle::stringf("S%d.tgf", child);
        ret["tgf-format"] = (int)1;

        return std::move(ret);
    }
};

using RootThread = Root <GenericCoupledModelThread>;
using RootMono = Root <GenericCoupledModelMono>;
using RootMPIThread = RootMPI <GenericCoupledModelThread>;
using RootMPIMono = RootMPI <GenericCoupledModelMono>;
using CoupledThread = Coupled <GenericCoupledModelThread>;
using CoupledMono = Coupled <GenericCoupledModelMono>;

}

#endif
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

/**
 * @file conti_radar_message_manager.h
 * @brief The class of ContiRadarMessageManager
 */

#include "modules/drivers/conti_radar/conti_radar_message_manager.h"

#include "modules/drivers/conti_radar/protocol/cluster_general_info_701.h"
#include "modules/drivers/conti_radar/protocol/cluster_list_status_600.h"
#include "modules/drivers/conti_radar/protocol/cluster_quality_info_702.h"
#include "modules/drivers/conti_radar/protocol/object_extended_info_60d.h"
#include "modules/drivers/conti_radar/protocol/object_general_info_60b.h"
#include "modules/drivers/conti_radar/protocol/object_list_status_60a.h"
#include "modules/drivers/conti_radar/protocol/object_quality_info_60c.h"
#include "modules/drivers/conti_radar/protocol/radar_state_201.h"

namespace apollo {
namespace drivers {
namespace conti_radar {

using ::apollo::common::adapter::AdapterManager;

ContiRadarMessageManager::ContiRadarMessageManager() {
  AddRecvProtocolData<RadarState201, true>();
  AddRecvProtocolData<ClusterListStatus600, true>();
  AddRecvProtocolData<ClusterGeneralInfo701, true>();
  AddRecvProtocolData<ClusterQualityInfo702, true>();
  AddRecvProtocolData<ObjectExtendedInfo60D, true>();
  AddRecvProtocolData<ObjectGeneralInfo60B, true>();
  AddRecvProtocolData<ObjectListStatus60A, true>();
  AddRecvProtocolData<ObjectQualityInfo60C, true>();
}

void ContiRadarMessageManager::set_radar_conf(RadarConf radar_conf) {
  radar_config_.set_radar_conf(radar_conf);
}

void ContiRadarMessageManager::set_can_client(
    std::shared_ptr<CanClient> can_client) {
  can_client_ = can_client;
}

ProtocolData<ContiRadar> *ContiRadarMessageManager::GetMutableProtocolDataById(
    const uint32_t message_id) {
  uint32_t converted_message_id = message_id;
  if (protocol_data_map_.find(converted_message_id) ==
      protocol_data_map_.end()) {
    ADEBUG << "Unable to get protocol data because of invalid message_id:"
           << message_id;
    return nullptr;
  }
  return protocol_data_map_[converted_message_id];
}

void ContiRadarMessageManager::Parse(const uint32_t message_id,
                                     const uint8_t *data, int32_t length) {
  if (length != ::apollo::drivers::canbus::CANBUS_MESSAGE_LENGTH) {
    AERROR << "Incorrect ContiRadar message length, length:" << length
           << " required length: "
           << ::apollo::drivers::canbus::CANBUS_MESSAGE_LENGTH;
    return;
  }

  ProtocolData<ContiRadar> *sensor_protocol_data =
      GetMutableProtocolDataById(message_id);
  if (sensor_protocol_data == nullptr) {
    return;
  }

  std::lock_guard<std::mutex> lock(sensor_data_mutex_);
  if (!is_configured_ && message_id != 0x201) {
    // read radar state message first
    return;
  }

  // trigger publishment
  if (message_id == 0x600 || message_id == 0x60A) {
    ADEBUG << sensor_data_.ShortDebugString();

    if (sensor_data_.contiobs_size() <=
        sensor_data_.object_list_status().nof_objects()) {
      // maybe lost a object_list_status msg
      AdapterManager::PublishContiRadar(sensor_data_);
    }
    sensor_data_.Clear();
    // fill header when recieve the general info message
    AdapterManager::FillContiRadarHeader(FLAGS_sensor_node_name, &sensor_data_);
  }

  sensor_protocol_data->Parse(data, length, &sensor_data_);

  if (message_id == 0x201) {
    ADEBUG << sensor_data_.ShortDebugString();
    if (sensor_data_.radar_state().send_quality() ==
            radar_config_.radar_conf().send_quality() &&
        sensor_data_.radar_state().send_ext_info() ==
            radar_config_.radar_conf().send_ext_info() &&
        sensor_data_.radar_state().max_distance() ==
            radar_config_.radar_conf().max_distance() &&
        sensor_data_.radar_state().output_type() ==
            radar_config_.radar_conf().output_type() &&
        sensor_data_.radar_state().rcs_threshold() ==
            radar_config_.radar_conf().rcs_threshold() &&
        sensor_data_.radar_state().radar_power() ==
            radar_config_.radar_conf().radar_power()) {
      is_configured_ = true;
    } else {
      AINFO << "configure radar again";
      SenderMessage<ContiRadar> sender_message(RadarConfig200::ID,
                                               &radar_config_);
      sender_message.Update();
      can_client_->SendSingleFrame({sender_message.CanFrame()});
    }
  }

  received_ids_.insert(message_id);
  // check if need to check period
  const auto it = check_ids_.find(message_id);
  if (it != check_ids_.end()) {
    const int64_t time = apollo::common::time::AsInt64<micros>(Clock::Now());
    it->second.real_period = time - it->second.last_time;
    // if period 1.5 large than base period, inc error_count
    const double period_multiplier = 1.5;
    if (it->second.real_period > (it->second.period * period_multiplier)) {
      it->second.error_count += 1;
    } else {
      it->second.error_count = 0;
    }
    it->second.last_time = time;
  }
}

}  // namespace conti_radar
}  // namespace drivers
}  // namespace apollo
<commit_msg>conti_radar : temporary disable length check<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

/**
 * @file conti_radar_message_manager.h
 * @brief The class of ContiRadarMessageManager
 */

#include "modules/drivers/conti_radar/conti_radar_message_manager.h"

#include "modules/drivers/conti_radar/protocol/cluster_general_info_701.h"
#include "modules/drivers/conti_radar/protocol/cluster_list_status_600.h"
#include "modules/drivers/conti_radar/protocol/cluster_quality_info_702.h"
#include "modules/drivers/conti_radar/protocol/object_extended_info_60d.h"
#include "modules/drivers/conti_radar/protocol/object_general_info_60b.h"
#include "modules/drivers/conti_radar/protocol/object_list_status_60a.h"
#include "modules/drivers/conti_radar/protocol/object_quality_info_60c.h"
#include "modules/drivers/conti_radar/protocol/radar_state_201.h"

namespace apollo {
namespace drivers {
namespace conti_radar {

using ::apollo::common::adapter::AdapterManager;

ContiRadarMessageManager::ContiRadarMessageManager() {
  AddRecvProtocolData<RadarState201, true>();
  AddRecvProtocolData<ClusterListStatus600, true>();
  AddRecvProtocolData<ClusterGeneralInfo701, true>();
  AddRecvProtocolData<ClusterQualityInfo702, true>();
  AddRecvProtocolData<ObjectExtendedInfo60D, true>();
  AddRecvProtocolData<ObjectGeneralInfo60B, true>();
  AddRecvProtocolData<ObjectListStatus60A, true>();
  AddRecvProtocolData<ObjectQualityInfo60C, true>();
}

void ContiRadarMessageManager::set_radar_conf(RadarConf radar_conf) {
  radar_config_.set_radar_conf(radar_conf);
}

void ContiRadarMessageManager::set_can_client(
    std::shared_ptr<CanClient> can_client) {
  can_client_ = can_client;
}

ProtocolData<ContiRadar> *ContiRadarMessageManager::GetMutableProtocolDataById(
    const uint32_t message_id) {
  uint32_t converted_message_id = message_id;
  if (protocol_data_map_.find(converted_message_id) ==
      protocol_data_map_.end()) {
    ADEBUG << "Unable to get protocol data because of invalid message_id:"
           << message_id;
    return nullptr;
  }
  return protocol_data_map_[converted_message_id];
}

void ContiRadarMessageManager::Parse(const uint32_t message_id,
                                     const uint8_t *data, int32_t length) {
  /*
if (length != ::apollo::drivers::canbus::CANBUS_MESSAGE_LENGTH) {
AERROR << "Incorrect ContiRadar message length, length:" << length
<< " required length: "
<< ::apollo::drivers::canbus::CANBUS_MESSAGE_LENGTH;
return;
}
*/
  ProtocolData<ContiRadar> *sensor_protocol_data =
      GetMutableProtocolDataById(message_id);
  if (sensor_protocol_data == nullptr) {
    return;
  }

  std::lock_guard<std::mutex> lock(sensor_data_mutex_);
  if (!is_configured_ && message_id != 0x201) {
    // read radar state message first
    return;
  }

  // trigger publishment
  if (message_id == 0x600 || message_id == 0x60A) {
    ADEBUG << sensor_data_.ShortDebugString();

    if (sensor_data_.contiobs_size() <=
        sensor_data_.object_list_status().nof_objects()) {
      // maybe lost a object_list_status msg
      AdapterManager::PublishContiRadar(sensor_data_);
    }
    sensor_data_.Clear();
    // fill header when recieve the general info message
    AdapterManager::FillContiRadarHeader(FLAGS_sensor_node_name, &sensor_data_);
  }

  sensor_protocol_data->Parse(data, length, &sensor_data_);

  if (message_id == 0x201) {
    ADEBUG << sensor_data_.ShortDebugString();
    if (sensor_data_.radar_state().send_quality() ==
            radar_config_.radar_conf().send_quality() &&
        sensor_data_.radar_state().send_ext_info() ==
            radar_config_.radar_conf().send_ext_info() &&
        sensor_data_.radar_state().max_distance() ==
            radar_config_.radar_conf().max_distance() &&
        sensor_data_.radar_state().output_type() ==
            radar_config_.radar_conf().output_type() &&
        sensor_data_.radar_state().rcs_threshold() ==
            radar_config_.radar_conf().rcs_threshold() &&
        sensor_data_.radar_state().radar_power() ==
            radar_config_.radar_conf().radar_power()) {
      is_configured_ = true;
    } else {
      AINFO << "configure radar again";
      SenderMessage<ContiRadar> sender_message(RadarConfig200::ID,
                                               &radar_config_);
      sender_message.Update();
      can_client_->SendSingleFrame({sender_message.CanFrame()});
    }
  }

  received_ids_.insert(message_id);
  // check if need to check period
  const auto it = check_ids_.find(message_id);
  if (it != check_ids_.end()) {
    const int64_t time = apollo::common::time::AsInt64<micros>(Clock::Now());
    it->second.real_period = time - it->second.last_time;
    // if period 1.5 large than base period, inc error_count
    const double period_multiplier = 1.5;
    if (it->second.real_period > (it->second.period * period_multiplier)) {
      it->second.error_count += 1;
    } else {
      it->second.error_count = 0;
    }
    it->second.last_time = time;
  }
}

}  // namespace conti_radar
}  // namespace drivers
}  // namespace apollo
<|endoftext|>


<commit_before>// Copyright (c) 2010 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 "app/l10n_util.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/login/account_screen.h"
#include "chrome/browser/chromeos/login/language_switch_model.h"
#include "chrome/browser/chromeos/login/mock_update_screen.h"
#include "chrome/browser/chromeos/login/network_screen.h"
#include "chrome/browser/chromeos/login/network_selection_view.h"
#include "chrome/browser/chromeos/login/wizard_controller.h"
#include "chrome/browser/chromeos/login/wizard_in_process_browser_test.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/ui_test_utils.h"
#include "grit/generated_resources.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "unicode/locid.h"

namespace {

template <class T>
class MockOutShowHide : public T {
 public:
  template <class P> MockOutShowHide(P p) : T(p) {}
  template <class P1, class P2> MockOutShowHide(P1 p1, P2 p2) : T(p1, p2) {}
  MOCK_METHOD0(Show, void());
  MOCK_METHOD0(Hide, void());
};

template <class T>
struct CreateMockWizardScreenHelper {
  static MockOutShowHide<T>* Create(WizardController* wizard);
};

template <class T> MockOutShowHide<T>*
CreateMockWizardScreenHelper<T>::Create(WizardController* wizard) {
  return new MockOutShowHide<T>(wizard);
}

template <> MockOutShowHide<chromeos::NetworkScreen>*
CreateMockWizardScreenHelper<chromeos::NetworkScreen>::Create(
    WizardController* wizard) {
  return new MockOutShowHide<chromeos::NetworkScreen>(wizard, true);
}

#define MOCK(mock_var, screen_name, mocked_class)                              \
  mock_var = CreateMockWizardScreenHelper<mocked_class>::Create(controller()); \
  controller()->screen_name.reset(mock_var);                                   \
  EXPECT_CALL(*mock_var, Show()).Times(0);                                     \
  EXPECT_CALL(*mock_var, Hide()).Times(0);

}  // namespace

class WizardControllerTest : public chromeos::WizardInProcessBrowserTest {
 protected:
  WizardControllerTest() : chromeos::WizardInProcessBrowserTest(
      WizardController::kTestNoScreenName) {}
  virtual ~WizardControllerTest() {}

 private:
  DISALLOW_COPY_AND_ASSIGN(WizardControllerTest);
};

IN_PROC_BROWSER_TEST_F(WizardControllerTest, SwitchLanguage) {
  WizardController* const wizard = controller();
  ASSERT_TRUE(wizard != NULL);
  wizard->ShowFirstScreen(WizardController::kOutOfBoxScreenName);
  views::View* current_screen = wizard->contents();
  ASSERT_TRUE(current_screen != NULL);

  // Checking the default locale. Provided that the profile is cleared in SetUp.
  EXPECT_EQ("en-US", g_browser_process->GetApplicationLocale());
  EXPECT_STREQ("en", icu::Locale::getDefault().getLanguage());
  EXPECT_FALSE(current_screen->UILayoutIsRightToLeft());
  const std::wstring en_str = l10n_util::GetString(IDS_NETWORK_SELECTION_TITLE);

  chromeos::LanguageSwitchModel::SwitchLanguage("fr");
  EXPECT_EQ("fr", g_browser_process->GetApplicationLocale());
  EXPECT_STREQ("fr", icu::Locale::getDefault().getLanguage());
  EXPECT_FALSE(current_screen->UILayoutIsRightToLeft());
  const std::wstring fr_str = l10n_util::GetString(IDS_NETWORK_SELECTION_TITLE);

  EXPECT_NE(en_str, fr_str);

  chromeos::LanguageSwitchModel::SwitchLanguage("ar");
  EXPECT_EQ("ar", g_browser_process->GetApplicationLocale());
  EXPECT_STREQ("ar", icu::Locale::getDefault().getLanguage());
  EXPECT_TRUE(current_screen->UILayoutIsRightToLeft());
  const std::wstring ar_str = l10n_util::GetString(IDS_NETWORK_SELECTION_TITLE);

  EXPECT_NE(fr_str, ar_str);
}

class WizardControllerFlowTest : public WizardControllerTest {
 protected:
  WizardControllerFlowTest() {}
  // Overriden from InProcessBrowserTest:
  virtual Browser* CreateBrowser(Profile* profile) {
    Browser* ret = WizardControllerTest::CreateBrowser(profile);

    // Set up the mocks for all screens.
    MOCK(mock_account_screen_, account_screen_, chromeos::AccountScreen);
    MOCK(mock_login_screen_, login_screen_, LoginScreen);
    MOCK(mock_network_screen_, network_screen_, chromeos::NetworkScreen);
    MOCK(mock_update_screen_, update_screen_, MockUpdateScreen);

    // Switch to the initial screen.
    EXPECT_EQ(NULL, controller()->current_screen());
    EXPECT_CALL(*mock_network_screen_, Show()).Times(1);
    controller()->ShowFirstScreen(WizardController::kOutOfBoxScreenName);

    return ret;
  }

  MockOutShowHide<chromeos::AccountScreen>* mock_account_screen_;
  MockOutShowHide<LoginScreen>* mock_login_screen_;
  MockOutShowHide<chromeos::NetworkScreen>* mock_network_screen_;
  MockOutShowHide<MockUpdateScreen>* mock_update_screen_;

 private:
  DISALLOW_COPY_AND_ASSIGN(WizardControllerFlowTest);
};

IN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, ControlFlowMain) {
  EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen());
  EXPECT_CALL(*mock_network_screen_, Hide()).Times(1);
  EXPECT_CALL(*mock_update_screen_, StartUpdate()).Times(1);
  EXPECT_CALL(*mock_update_screen_, Show()).Times(1);
  controller()->OnExit(chromeos::ScreenObserver::NETWORK_CONNECTED);

  EXPECT_EQ(controller()->GetUpdateScreen(), controller()->current_screen());
  EXPECT_CALL(*mock_update_screen_, Hide()).Times(1);
  EXPECT_CALL(*mock_login_screen_, Show()).Times(1);
  controller()->OnExit(chromeos::ScreenObserver::UPDATE_INSTALLED);

  EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen());
  EXPECT_CALL(*mock_login_screen_, Hide()).Times(1);
  EXPECT_CALL(*mock_account_screen_, Show()).Times(1);
  controller()->OnExit(chromeos::ScreenObserver::LOGIN_CREATE_ACCOUNT);

  EXPECT_EQ(controller()->GetAccountScreen(), controller()->current_screen());
  EXPECT_CALL(*mock_account_screen_, Hide()).Times(1);
  EXPECT_CALL(*mock_login_screen_, Show()).Times(1);
  EXPECT_CALL(*mock_login_screen_, Hide()).Times(0);  // last transition
  controller()->OnExit(chromeos::ScreenObserver::ACCOUNT_CREATED);

  EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen());
}

IN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, ControlFlowErrorUpdate) {
  EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen());
  EXPECT_CALL(*mock_update_screen_, StartUpdate()).Times(1);
  EXPECT_CALL(*mock_update_screen_, Show()).Times(1);
  EXPECT_CALL(*mock_network_screen_, Hide()).Times(1);
  controller()->OnExit(chromeos::ScreenObserver::NETWORK_CONNECTED);

  EXPECT_EQ(controller()->GetUpdateScreen(), controller()->current_screen());
  EXPECT_CALL(*mock_update_screen_, Hide()).Times(1);
  EXPECT_CALL(*mock_network_screen_, Show()).Times(1);
  EXPECT_CALL(*mock_network_screen_, Hide()).Times(0);  // last transition
  controller()->OnExit(chromeos::ScreenObserver::UPDATE_NETWORK_ERROR);

  EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen());
}

IN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, ControlFlowErrorNetwork) {
  EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen());
  EXPECT_CALL(*mock_login_screen_, Show()).Times(1);
  EXPECT_CALL(*mock_network_screen_, Hide()).Times(1);
  controller()->OnExit(chromeos::ScreenObserver::NETWORK_OFFLINE);
  EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen());
}

COMPILE_ASSERT(chromeos::ScreenObserver::EXIT_CODES_COUNT == 11,
               add_tests_for_new_control_flow_you_just_introduced);
<commit_msg>Attempted ChromiumOS compile fix.<commit_after>// Copyright (c) 2010 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 "app/l10n_util.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/login/account_screen.h"
#include "chrome/browser/chromeos/login/language_switch_model.h"
#include "chrome/browser/chromeos/login/mock_update_screen.h"
#include "chrome/browser/chromeos/login/network_screen.h"
#include "chrome/browser/chromeos/login/network_selection_view.h"
#include "chrome/browser/chromeos/login/wizard_controller.h"
#include "chrome/browser/chromeos/login/wizard_in_process_browser_test.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/ui_test_utils.h"
#include "grit/generated_resources.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "unicode/locid.h"

namespace {

template <class T>
class MockOutShowHide : public T {
 public:
  template <class P> MockOutShowHide(P p) : T(p) {}
  template <class P1, class P2> MockOutShowHide(P1 p1, P2 p2) : T(p1, p2) {}
  MOCK_METHOD0(Show, void());
  MOCK_METHOD0(Hide, void());
};

template <class T>
struct CreateMockWizardScreenHelper {
  static MockOutShowHide<T>* Create(WizardController* wizard);
};

template <class T> MockOutShowHide<T>*
CreateMockWizardScreenHelper<T>::Create(WizardController* wizard) {
  return new MockOutShowHide<T>(wizard);
}

template <> MockOutShowHide<chromeos::NetworkScreen>*
CreateMockWizardScreenHelper<chromeos::NetworkScreen>::Create(
    WizardController* wizard) {
  return new MockOutShowHide<chromeos::NetworkScreen>(wizard, true);
}

#define MOCK(mock_var, screen_name, mocked_class)                              \
  mock_var = CreateMockWizardScreenHelper<mocked_class>::Create(controller()); \
  controller()->screen_name.reset(mock_var);                                   \
  EXPECT_CALL(*mock_var, Show()).Times(0);                                     \
  EXPECT_CALL(*mock_var, Hide()).Times(0);

}  // namespace

class WizardControllerTest : public chromeos::WizardInProcessBrowserTest {
 protected:
  WizardControllerTest() : chromeos::WizardInProcessBrowserTest(
      WizardController::kTestNoScreenName) {}
  virtual ~WizardControllerTest() {}

 private:
  DISALLOW_COPY_AND_ASSIGN(WizardControllerTest);
};

IN_PROC_BROWSER_TEST_F(WizardControllerTest, SwitchLanguage) {
  WizardController* const wizard = controller();
  ASSERT_TRUE(wizard != NULL);
  wizard->ShowFirstScreen(WizardController::kOutOfBoxScreenName);
  views::View* current_screen = wizard->contents();
  ASSERT_TRUE(current_screen != NULL);

  // Checking the default locale. Provided that the profile is cleared in SetUp.
  EXPECT_EQ("en-US", g_browser_process->GetApplicationLocale());
  EXPECT_STREQ("en", icu::Locale::getDefault().getLanguage());
  EXPECT_FALSE(base::i18n::IsRTL());
  const std::wstring en_str = l10n_util::GetString(IDS_NETWORK_SELECTION_TITLE);

  chromeos::LanguageSwitchModel::SwitchLanguage("fr");
  EXPECT_EQ("fr", g_browser_process->GetApplicationLocale());
  EXPECT_STREQ("fr", icu::Locale::getDefault().getLanguage());
  EXPECT_FALSE(base::i18n::IsRTL());
  const std::wstring fr_str = l10n_util::GetString(IDS_NETWORK_SELECTION_TITLE);

  EXPECT_NE(en_str, fr_str);

  chromeos::LanguageSwitchModel::SwitchLanguage("ar");
  EXPECT_EQ("ar", g_browser_process->GetApplicationLocale());
  EXPECT_STREQ("ar", icu::Locale::getDefault().getLanguage());
  EXPECT_TRUE(base::i18n::IsRTL());
  const std::wstring ar_str = l10n_util::GetString(IDS_NETWORK_SELECTION_TITLE);

  EXPECT_NE(fr_str, ar_str);
}

class WizardControllerFlowTest : public WizardControllerTest {
 protected:
  WizardControllerFlowTest() {}
  // Overriden from InProcessBrowserTest:
  virtual Browser* CreateBrowser(Profile* profile) {
    Browser* ret = WizardControllerTest::CreateBrowser(profile);

    // Set up the mocks for all screens.
    MOCK(mock_account_screen_, account_screen_, chromeos::AccountScreen);
    MOCK(mock_login_screen_, login_screen_, LoginScreen);
    MOCK(mock_network_screen_, network_screen_, chromeos::NetworkScreen);
    MOCK(mock_update_screen_, update_screen_, MockUpdateScreen);

    // Switch to the initial screen.
    EXPECT_EQ(NULL, controller()->current_screen());
    EXPECT_CALL(*mock_network_screen_, Show()).Times(1);
    controller()->ShowFirstScreen(WizardController::kOutOfBoxScreenName);

    return ret;
  }

  MockOutShowHide<chromeos::AccountScreen>* mock_account_screen_;
  MockOutShowHide<LoginScreen>* mock_login_screen_;
  MockOutShowHide<chromeos::NetworkScreen>* mock_network_screen_;
  MockOutShowHide<MockUpdateScreen>* mock_update_screen_;

 private:
  DISALLOW_COPY_AND_ASSIGN(WizardControllerFlowTest);
};

IN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, ControlFlowMain) {
  EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen());
  EXPECT_CALL(*mock_network_screen_, Hide()).Times(1);
  EXPECT_CALL(*mock_update_screen_, StartUpdate()).Times(1);
  EXPECT_CALL(*mock_update_screen_, Show()).Times(1);
  controller()->OnExit(chromeos::ScreenObserver::NETWORK_CONNECTED);

  EXPECT_EQ(controller()->GetUpdateScreen(), controller()->current_screen());
  EXPECT_CALL(*mock_update_screen_, Hide()).Times(1);
  EXPECT_CALL(*mock_login_screen_, Show()).Times(1);
  controller()->OnExit(chromeos::ScreenObserver::UPDATE_INSTALLED);

  EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen());
  EXPECT_CALL(*mock_login_screen_, Hide()).Times(1);
  EXPECT_CALL(*mock_account_screen_, Show()).Times(1);
  controller()->OnExit(chromeos::ScreenObserver::LOGIN_CREATE_ACCOUNT);

  EXPECT_EQ(controller()->GetAccountScreen(), controller()->current_screen());
  EXPECT_CALL(*mock_account_screen_, Hide()).Times(1);
  EXPECT_CALL(*mock_login_screen_, Show()).Times(1);
  EXPECT_CALL(*mock_login_screen_, Hide()).Times(0);  // last transition
  controller()->OnExit(chromeos::ScreenObserver::ACCOUNT_CREATED);

  EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen());
}

IN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, ControlFlowErrorUpdate) {
  EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen());
  EXPECT_CALL(*mock_update_screen_, StartUpdate()).Times(1);
  EXPECT_CALL(*mock_update_screen_, Show()).Times(1);
  EXPECT_CALL(*mock_network_screen_, Hide()).Times(1);
  controller()->OnExit(chromeos::ScreenObserver::NETWORK_CONNECTED);

  EXPECT_EQ(controller()->GetUpdateScreen(), controller()->current_screen());
  EXPECT_CALL(*mock_update_screen_, Hide()).Times(1);
  EXPECT_CALL(*mock_network_screen_, Show()).Times(1);
  EXPECT_CALL(*mock_network_screen_, Hide()).Times(0);  // last transition
  controller()->OnExit(chromeos::ScreenObserver::UPDATE_NETWORK_ERROR);

  EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen());
}

IN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, ControlFlowErrorNetwork) {
  EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen());
  EXPECT_CALL(*mock_login_screen_, Show()).Times(1);
  EXPECT_CALL(*mock_network_screen_, Hide()).Times(1);
  controller()->OnExit(chromeos::ScreenObserver::NETWORK_OFFLINE);
  EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen());
}

COMPILE_ASSERT(chromeos::ScreenObserver::EXIT_CODES_COUNT == 11,
               add_tests_for_new_control_flow_you_just_introduced);
<|endoftext|>


<commit_before>//
//  calcPWP.cpp
//
//
//  Created by Evan McCartney-Melstad on 1/10/15.
//
//

#include "calcPWP.h"
#include <iostream>
#include <vector>
#include <fstream>
#include <thread>
#include <string>

int calcPWPfromBinaryFile (std::string binaryFile, unsigned long long int numLoci, const int numIndividuals, std::string outFile, int numThreads) {

    //****MODIFY THIS TO ONLY READ IN N LOCI AT A TIME, INSTEAD OF USING THE ENTIRE FILE****

    std::cout << "Number of threads: " << numThreads << std::endl;
    std::streampos size;
    std::ifstream file (binaryFile, std::ios::in|std::ios::binary|std::ios::ate);
    //ifstream file ("test500k.binary8bitunsigned", ios::in|ios::binary|ios::ate);
    if (file.is_open()) {
        size = file.tellg(); // Just a variable that shows position of stream--at end since ios::ate, so it's the file size. PROBABLY WON'T WORK FOR FILES LARGER THAN ~ 2GB!
        file.seekg (0, std::ios::beg); // Go back to the beginning of the file
        //file.read((char*)readCounts, size); // cast to a char* to give to file.read

        //unsigned char* readCounts;
        //readCounts = new unsigned char[size];
        std::vector<unsigned char> readCounts(size);
        file.read((char*) &readCounts[0], size);
        file.close();

        std::cout << "the entire file content is in memory" << std::endl;
        std::cout << "the total size of the file is " << size << std::endl;
        std::cout << "the number of elements in the readCounts vector is: " << readCounts.size() << std::endl; // Will give the total size bytes divided by the size of one element--so it gives the number of elements

        /* We are going to split the loci between numThreads threads. Each thread will modify two multidimensional
         vectors of the forms std::vector< std::vector<long double> > pwp(numIndividuals, std::vector<long double>(numIndividuals,0))    and   std::vector< std::vector<unsigned long long int> > weightings(numIndividuals, std::vector<unsigned long long int>(numIndividuals,0))

         First, we'll generate all of these vectors, which apparently in C++ needs to be constructed of a
         vector of two-dimensional vectors...
         */
        std::vector<std::vector<std::vector<long double>>> pwpThreads(numThreads, std::vector<std::vector<long double>> (numIndividuals, std::vector<long double> (numIndividuals,0) ) ); //pwpThreads[0] is the first 2D array for the first thread, etc...
        std::vector<std::vector<std::vector<unsigned long long int>>> weightingsThreads(numThreads, std::vector<std::vector<unsigned long long int> > (numIndividuals, std::vector<unsigned long long int> (numIndividuals,0) ) );

        std::cout << "Initialized the 3d vectors" << std::endl;

        // Now we need to determine how many loci for each thread. If we want to use the entire binary file, instead of numLoci loci, then change this to lociPerThread = (size/(numIndividuals*2))/numThreads
        //unsigned long long int lociPerThread = numLoci / numThreads;

        //unsigned long long int lociPerThread = (readCounts.size()-1)/numThreads; // loci starts with 0, so need to subtract 1 from numLoci
        unsigned long long int lociPerThread;
        if (numLoci == 0) {
            lociPerThread = (unsigned long long)(size/(numIndividuals*2))/(unsigned long long)numThreads;
        } else {
            lociPerThread = (unsigned long long)numLoci/(unsigned long long)numThreads;
        }

        std::cout << "Initialized lociPerThread with " << numLoci << std::endl;

        std::vector<std::thread> threadsVec;
        for (int threadRunning = 0; threadRunning < numThreads; threadRunning++) {
            std::cout << "Got to the function call. Running thread # " << threadRunning << std::endl;
            unsigned long long int firstLocus = (unsigned long long int) threadRunning * lociPerThread;
            unsigned long long int finishingLocus = ((unsigned long long int) threadRunning * lociPerThread) + lociPerThread - (unsigned long long)1.0;
            std::cout << "Set firstLocus to " << firstLocus << " and finishingLocus to " << finishingLocus << std::endl;

            threadsVec.push_back(std::thread(calcPWPforRange, firstLocus, finishingLocus, numIndividuals, std::ref(readCounts), std::ref(pwpThreads[threadRunning]), std::ref(weightingsThreads[threadRunning])));
        }

        // Wait on threads to finish
        for (int i = 0; i < numThreads; ++i) {
            threadsVec[i].join();
            std::cout << "Joined thread " << i << std::endl;
        }
        std::cout << "All threads completed running" << std::endl;

        // Now aggregate the results of the threads and print final results
        std::vector<std::vector<long double>> weightingsSum(numIndividuals, std::vector<long double>(numIndividuals,0));
        std::vector<std::vector<long double>> pwpSum(numIndividuals, std::vector<long double>(numIndividuals,0));

        for (int tortoise = 0; tortoise < numIndividuals; tortoise++) {
            for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) {
                for (int threadVector = 0; threadVector < numThreads; threadVector++) {
                    weightingsSum[tortoise][comparisonTortoise] += weightingsThreads[threadVector][tortoise][comparisonTortoise];
                    pwpSum[tortoise][comparisonTortoise] += pwpThreads[threadVector][tortoise][comparisonTortoise];
                }
            }
        }

        std::cout << "Finished summing the threads vectors" << std::endl;

        // Now print out the final output to the pairwise pi file:
        std::ofstream pwpOUT (outFile);
        int rowCounter = 0;
        if (!pwpOUT) {
            std::cerr << "Crap, " << outFile << "didn't open!" << std::endl;
        } else {
            for (int tortoise=0; tortoise < numIndividuals; tortoise++) {
                for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) {
                    rowCounter++;

                    //std::cout << "Made it past the beginning of the last end for loop" << std::endl;
                    //std::cout << "Tortoise numbers: " << tortoise << " and " << comparisonTortoise << std::endl;
                    if (weightingsSum[tortoise][comparisonTortoise] > 0) {
                        //std::cout << weightings[tortoise][comparisonTortoise] << std::endl;
                        //std::cout << pwp[tortoise][comparisonTortoise] / weightings[tortoise][comparisonTortoise] << std::endl;
                        std::cout << std::fixed;
                        std::cout << "Weightings for tortoise " << tortoise << " and comparisonTortoise " << comparisonTortoise << " : " << weightingsSum[tortoise][comparisonTortoise] << std::endl;
                        std::cout << "PWP for tortoise " << tortoise << " and comparisonTortoise " << comparisonTortoise << " : " << pwpSum[tortoise][comparisonTortoise] << std::endl;
                        std::cout << std::scientific;
                        pwpOUT << pwpSum[tortoise][comparisonTortoise] / weightingsSum[tortoise][comparisonTortoise] << std::endl;
                    } else {
                        pwpOUT << "NA" << std::endl;
                    }
                }
            }
        }
    } else std::cout << "Unable to open file";

    return 0;
}

//int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, const std::vector<BYTE>& mainReadCountVector, std::vector< std::vector<long double> > & threadPWP, std::vector< std::vector<long double> > & threadWeightings) {
int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, std::vector<unsigned char>& mainReadCountVector, std::vector<std::vector<long double>>& threadPWP, std::vector<std::vector<unsigned long long int>>& threadWeightings) {

     std::cout << "Calculating PWP for the following locus range: " << startingLocus << " to " << endingLocus << std::endl;
     for( unsigned long long locus = startingLocus; locus < endingLocus; locus++) {
     //std::cout << "Processing locus # " << locus << std::endl;
         if (locus % 100000 == 0) {
             std::cout << locus << " loci processed through calcPWPfromBinaryFile" << std::endl;
         }

         int coverages[numIndividuals];
         long double *majorAlleleFreqs = new long double[numIndividuals]; // This will hold the major allele frequencies for that locus for each tortoise

         for( int tortoise = 0; tortoise < numIndividuals; tortoise++ ) {
             unsigned long long majorIndex = locus * (numIndividuals*2) + 2 * tortoise;
             unsigned long long minorIndex = locus * (numIndividuals*2) + 2 * tortoise + 1;

             coverages[tortoise] = int(mainReadCountVector[majorIndex]) + int(mainReadCountVector[minorIndex]); // Hold the coverages for each locus
             if ( coverages[tortoise] > 0 ) {
                 //std::cout << "Made it to line 222 for locus " << locus << std::endl;
                 majorAlleleFreqs[tortoise] = (long double)mainReadCountVector[majorIndex] / (long double)coverages[tortoise]; // Not necessarily an int, but could be 0 or 1

                 if (coverages[tortoise] > 1) {
                     unsigned long long locusWeighting = coverages[tortoise]*(coverages[tortoise]-1);
                     threadWeightings[tortoise][tortoise] += (unsigned long long)locusWeighting; // This is an int--discrete number of reads

                     threadPWP[tortoise][tortoise] += (long double)(locusWeighting) * ((long double)2.0 * majorAlleleFreqs[tortoise] * ((long double)(coverages[tortoise]) - (long double)(mainReadCountVector[majorIndex]))) / (long double)((coverages[tortoise])-(long double)1.0);
                 }

                 for( int comparisonTortoise = 0; comparisonTortoise < tortoise; comparisonTortoise++) {
                     if (coverages[comparisonTortoise] > 0) {
                         long double locusWeighting = (long double)coverages[tortoise] * (long double)(coverages[comparisonTortoise]-1.0);

                         threadWeightings[tortoise][comparisonTortoise] += locusWeighting;
                         threadPWP[tortoise][comparisonTortoise] += (long double)locusWeighting * (majorAlleleFreqs[tortoise] * ((long double)1.0-majorAlleleFreqs[comparisonTortoise]) + majorAlleleFreqs[comparisonTortoise] * ((long double)1.0-majorAlleleFreqs[tortoise]));
                    }
                }
            }
        }
        delete[] majorAlleleFreqs; // Needed to avoid memory leaks
    }
    std::cout << "Finished thread ending on locus " << endingLocus << std::endl;
    return 0;
}

<commit_msg>Minor changes<commit_after>//
//  calcPWP.cpp
//
//
//  Created by Evan McCartney-Melstad on 1/10/15.
//
//

#include "calcPWP.h"
#include <iostream>
#include <vector>
#include <fstream>
#include <thread>
#include <string>

int calcPWPfromBinaryFile (std::string binaryFile, unsigned long long int numLoci, const int numIndividuals, std::string outFile, int numThreads) {

    //****MODIFY THIS TO ONLY READ IN N LOCI AT A TIME, INSTEAD OF USING THE ENTIRE FILE****

    std::cout << "Number of threads: " << numThreads << std::endl;
    std::streampos size;
    std::ifstream file (binaryFile, std::ios::in|std::ios::binary|std::ios::ate);
    //ifstream file ("test500k.binary8bitunsigned", ios::in|ios::binary|ios::ate);
    if (file.is_open()) {
        size = file.tellg(); // Just a variable that shows position of stream--at end since ios::ate, so it's the file size. PROBABLY WON'T WORK FOR FILES LARGER THAN ~ 2GB!
        file.seekg (0, std::ios::beg); // Go back to the beginning of the file
        //file.read((char*)readCounts, size); // cast to a char* to give to file.read

        //unsigned char* readCounts;
        //readCounts = new unsigned char[size];
        std::vector<unsigned char> readCounts(size);
        file.read((char*) &readCounts[0], size);
        file.close();

        std::cout << "the entire file content is in memory" << std::endl;
        std::cout << "the total size of the file is " << size << std::endl;
        std::cout << "the number of elements in the readCounts vector is: " << readCounts.size() << std::endl; // Will give the total size bytes divided by the size of one element--so it gives the number of elements

        /* We are going to split the loci between numThreads threads. Each thread will modify two multidimensional
         vectors of the forms std::vector< std::vector<long double> > pwp(numIndividuals, std::vector<long double>(numIndividuals,0))    and   std::vector< std::vector<unsigned long long int> > weightings(numIndividuals, std::vector<unsigned long long int>(numIndividuals,0))

         First, we'll generate all of these vectors, which apparently in C++ needs to be constructed of a
         vector of two-dimensional vectors...
         */
        std::vector<std::vector<std::vector<long double>>> pwpThreads(numThreads, std::vector<std::vector<long double>> (numIndividuals, std::vector<long double> (numIndividuals,0) ) ); //pwpThreads[0] is the first 2D array for the first thread, etc...
        std::vector<std::vector<std::vector<unsigned long long int>>> weightingsThreads(numThreads, std::vector<std::vector<unsigned long long int> > (numIndividuals, std::vector<unsigned long long int> (numIndividuals,0) ) );

        std::cout << "Initialized the 3d vectors" << std::endl;

        // Now we need to determine how many loci for each thread. If we want to use the entire binary file, instead of numLoci loci, then change this to lociPerThread = (size/(numIndividuals*2))/numThreads
        //unsigned long long int lociPerThread = numLoci / numThreads;

        //unsigned long long int lociPerThread = (readCounts.size()-1)/numThreads; // loci starts with 0, so need to subtract 1 from numLoci
        unsigned long long int lociPerThread;
        if (numLoci == 0) {
            lociPerThread = (unsigned long long)(size/(numIndividuals*2))/(unsigned long long)numThreads;
        } else {
            lociPerThread = (unsigned long long)numLoci/(unsigned long long)numThreads;
        }

        std::cout << "Initialized lociPerThread with " << numLoci << std::endl;

        std::vector<std::thread> threadsVec;
        for (int threadRunning = 0; threadRunning < numThreads; threadRunning++) {
            std::cout << "Got to the function call. Running thread # " << threadRunning << std::endl;
            unsigned long long int firstLocus = (unsigned long long int) threadRunning * lociPerThread;
            unsigned long long int finishingLocus = ((unsigned long long int) threadRunning * lociPerThread) + lociPerThread - (unsigned long long)1.0;
            std::cout << "Set firstLocus to " << firstLocus << " and finishingLocus to " << finishingLocus << std::endl;

            threadsVec.push_back(std::thread(calcPWPforRange, firstLocus, finishingLocus, numIndividuals, std::ref(readCounts), std::ref(pwpThreads[threadRunning]), std::ref(weightingsThreads[threadRunning])));
        }

        // Wait on threads to finish
        for (int i = 0; i < numThreads; ++i) {
            threadsVec[i].join();
            std::cout << "Joined thread " << i << std::endl;
        }
        std::cout << "All threads completed running" << std::endl;

        // Now aggregate the results of the threads and print final results
        std::vector<std::vector<long double>> weightingsSum(numIndividuals, std::vector<long double>(numIndividuals,0));
        std::vector<std::vector<long double>> pwpSum(numIndividuals, std::vector<long double>(numIndividuals,0));

        for (int tortoise = 0; tortoise < numIndividuals; tortoise++) {
            for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) {
                for (int threadVector = 0; threadVector < numThreads; threadVector++) {
                    weightingsSum[tortoise][comparisonTortoise] += weightingsThreads[threadVector][tortoise][comparisonTortoise];
                    pwpSum[tortoise][comparisonTortoise] += pwpThreads[threadVector][tortoise][comparisonTortoise];
                }
            }
        }

        std::cout << "Finished summing the threads vectors" << std::endl;

        // Now print out the final output to the pairwise pi file:
        std::ofstream pwpOUT (outFile);
        int rowCounter = 0;
        if (!pwpOUT) {
            std::cerr << "Crap, " << outFile << "didn't open!" << std::endl;
        } else {
            for (int tortoise=0; tortoise < numIndividuals; tortoise++) {
                for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) {
                    rowCounter++;

                    //std::cout << "Made it past the beginning of the last end for loop" << std::endl;
                    //std::cout << "Tortoise numbers: " << tortoise << " and " << comparisonTortoise << std::endl;
                    if (weightingsSum[tortoise][comparisonTortoise] > 0) {
                        //std::cout << weightings[tortoise][comparisonTortoise] << std::endl;
                        //std::cout << pwp[tortoise][comparisonTortoise] / weightings[tortoise][comparisonTortoise] << std::endl;
                        std::cout << std::fixed;
                        std::cout << "Weightings for tortoise " << tortoise << " and comparisonTortoise " << comparisonTortoise << " : " << weightingsSum[tortoise][comparisonTortoise] << std::endl;
                        std::cout << "PWP for tortoise " << tortoise << " and comparisonTortoise " << comparisonTortoise << " : " << pwpSum[tortoise][comparisonTortoise] << std::endl;
                        std::cout << std::scientific;
                        pwpOUT << pwpSum[tortoise][comparisonTortoise] / weightingsSum[tortoise][comparisonTortoise] << std::endl;
                    } else {
                        pwpOUT << "NA" << std::endl;
                    }
                }
            }
        }
    } else std::cout << "Unable to open file";

    return 0;
}

//int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, const std::vector<BYTE>& mainReadCountVector, std::vector< std::vector<long double> > & threadPWP, std::vector< std::vector<long double> > & threadWeightings) {
int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, std::vector<unsigned char>& mainReadCountVector, std::vector<std::vector<long double>>& threadPWP, std::vector<std::vector<unsigned long long int>>& threadWeightings) {

     std::cout << "Calculating PWP for the following locus range: " << startingLocus << " to " << endingLocus << std::endl;
     for( unsigned long long locus = startingLocus; locus < endingLocus; locus++) {
     //std::cout << "Processing locus # " << locus << std::endl;
         if (locus % 100000 == 0) {
             std::cout << locus << " loci processed through calcPWPfromBinaryFile" << std::endl;
         }

         unsigned long long coverages[numIndividuals];
         long double *majorAlleleFreqs = new long double[numIndividuals]; // This will hold the major allele frequencies for that locus for each tortoise

         for( int tortoise = 0; tortoise < numIndividuals; tortoise++ ) {
             unsigned long long majorIndex = locus * (numIndividuals*2) + 2 * tortoise;
             unsigned long long minorIndex = locus * (numIndividuals*2) + 2 * tortoise + 1;

             coverages[tortoise] = int(mainReadCountVector[majorIndex]) + int(mainReadCountVector[minorIndex]); // Hold the coverages for each locus
             if ( coverages[tortoise] > 0 ) {
                 //std::cout << "Made it to line 222 for locus " << locus << std::endl;
                 majorAlleleFreqs[tortoise] = (long double)mainReadCountVector[majorIndex] / (long double)coverages[tortoise]; // Not necessarily an int, but could be 0 or 1

                 if (coverages[tortoise] > 1) {
                     unsigned long long locusWeighting = unsigned long long (coverages[tortoise]*(coverages[tortoise]-1));
                     threadWeightings[tortoise][tortoise] += (unsigned long long)locusWeighting; // This is an int--discrete number of reads

                     //threadPWP[tortoise][tortoise] += (long double)(locusWeighting) * ((long double)2.0 * majorAlleleFreqs[tortoise] * ((long double)(coverages[tortoise]) - (long double)(mainReadCountVector[majorIndex]))) / (long double)((coverages[tortoise])-(long double)1.0);
                     threadPWP[tortoise][tortoise] += (long double)(locusWeighting) * ((long double)2.0 * majorAlleleFreqs[tortoise] * ((long double)(coverages[tortoise]) - (long double)(mainReadCountVector[majorIndex]))) / (long double)((coverages[tortoise]));

                     //threadPWP[tortoise][tortoise] += locusWeighting*(2*majorAlleleFreqs[tortoise] * (coverages[tortoise]-majorReadCounts)) / (coverages[tortoise]-1)
                 }

                 for( int comparisonTortoise = 0; comparisonTortoise < tortoise; comparisonTortoise++) {
                     if (coverages[comparisonTortoise] > 0) {
                         long double locusWeighting = (long double)coverages[tortoise] * (long double)(coverages[comparisonTortoise]-1.0);

                         threadWeightings[tortoise][comparisonTortoise] += locusWeighting;
                         threadPWP[tortoise][comparisonTortoise] += (long double)locusWeighting * (majorAlleleFreqs[tortoise] * ((long double)1.0-majorAlleleFreqs[comparisonTortoise]) + majorAlleleFreqs[comparisonTortoise] * ((long double)1.0-majorAlleleFreqs[tortoise]));
                    }
                }
            }
        }
        delete[] majorAlleleFreqs; // Needed to avoid memory leaks
    }
    std::cout << "Finished thread ending on locus " << endingLocus << std::endl;
    return 0;
}

<|endoftext|>


<commit_before>// Copyright (c) 2012 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 "base/files/file_path.h"
#include "base/files/scoped_temp_dir.h"
#include "base/threading/sequenced_worker_pool.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_prefs.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/updater/extension_updater.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/global_error/global_error.h"
#include "chrome/browser/ui/global_error/global_error_service.h"
#include "chrome/browser/ui/global_error/global_error_service_factory.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/extension.h"
#include "content/test/net/url_request_prepackaged_interceptor.h"
#include "net/url_request/url_fetcher.h"

using extensions::Extension;

class ExtensionDisabledGlobalErrorTest : public ExtensionBrowserTest {
 protected:
  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    ExtensionBrowserTest::SetUpCommandLine(command_line);
    command_line->AppendSwitchASCII(switches::kAppsGalleryUpdateURL,
                                    "http://localhost/autoupdate/updates.xml");
  }

  virtual void SetUpOnMainThread() OVERRIDE {
    EXPECT_TRUE(scoped_temp_dir_.CreateUniqueTempDir());
    service_ = browser()->profile()->GetExtensionService();
    base::FilePath pem_path = test_data_dir_.
        AppendASCII("permissions_increase").AppendASCII("permissions.pem");
    path_v1_ = PackExtensionWithOptions(
        test_data_dir_.AppendASCII("permissions_increase").AppendASCII("v1"),
        scoped_temp_dir_.path().AppendASCII("permissions1.crx"),
        pem_path,
        base::FilePath());
    path_v2_ = PackExtensionWithOptions(
        test_data_dir_.AppendASCII("permissions_increase").AppendASCII("v2"),
        scoped_temp_dir_.path().AppendASCII("permissions2.crx"),
        pem_path,
        base::FilePath());
    path_v3_ = PackExtensionWithOptions(
        test_data_dir_.AppendASCII("permissions_increase").AppendASCII("v3"),
        scoped_temp_dir_.path().AppendASCII("permissions3.crx"),
        pem_path,
        base::FilePath());
  }

  // Returns the ExtensionDisabledGlobalError, if present.
  // Caution: currently only supports one error at a time.
  GlobalError* GetExtensionDisabledGlobalError() {
    return GlobalErrorServiceFactory::GetForProfile(browser()->profile())->
        GetGlobalErrorByMenuItemCommandID(IDC_EXTENSION_DISABLED_FIRST);
  }

  // Install the initial version, which should happen just fine.
  const Extension* InstallIncreasingPermissionExtensionV1() {
    size_t size_before = service_->extensions()->size();
    const Extension* extension = InstallExtension(path_v1_, 1);
    if (!extension)
      return NULL;
    if (service_->extensions()->size() != size_before + 1)
      return NULL;
    return extension;
  }

  // Upgrade to a version that wants more permissions. We should disable the
  // extension and prompt the user to reenable.
  const Extension* UpdateIncreasingPermissionExtension(
      const Extension* extension,
      const base::FilePath& crx_path,
      int expected_change) {
    size_t size_before = service_->extensions()->size();
    if (UpdateExtension(extension->id(), crx_path, expected_change))
      return NULL;
    BrowserThread::GetBlockingPool()->FlushForTesting();
    EXPECT_EQ(size_before + expected_change, service_->extensions()->size());
    if (service_->disabled_extensions()->size() != 1u)
      return NULL;

    return *service_->disabled_extensions()->begin();
  }

  // Helper function to install an extension and upgrade it to a version
  // requiring additional permissions. Returns the new disabled Extension.
  const Extension* InstallAndUpdateIncreasingPermissionsExtension() {
    const Extension* extension = InstallIncreasingPermissionExtensionV1();
    extension = UpdateIncreasingPermissionExtension(extension, path_v2_, -1);
    return extension;
  }

  ExtensionService* service_;
  base::ScopedTempDir scoped_temp_dir_;
  base::FilePath path_v1_;
  base::FilePath path_v2_;
  base::FilePath path_v3_;
};

// Tests the process of updating an extension to one that requires higher
// permissions, and accepting the permissions.
IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, AcceptPermissions) {
  const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();
  ASSERT_TRUE(extension);
  ASSERT_TRUE(GetExtensionDisabledGlobalError());
  const size_t size_before = service_->extensions()->size();

  service_->GrantPermissionsAndEnableExtension(extension);
  EXPECT_EQ(size_before + 1, service_->extensions()->size());
  EXPECT_EQ(0u, service_->disabled_extensions()->size());
  ASSERT_FALSE(GetExtensionDisabledGlobalError());
}

// Tests uninstalling an extension that was disabled due to higher permissions.
IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, Uninstall) {
  const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();
  ASSERT_TRUE(extension);
  ASSERT_TRUE(GetExtensionDisabledGlobalError());
  const size_t size_before = service_->extensions()->size();

  UninstallExtension(extension->id());
  EXPECT_EQ(size_before, service_->extensions()->size());
  EXPECT_EQ(0u, service_->disabled_extensions()->size());
  ASSERT_FALSE(GetExtensionDisabledGlobalError());
}

// Tests that no error appears if the user disabled the extension.
IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, UserDisabled) {
  const Extension* extension = InstallIncreasingPermissionExtensionV1();
  DisableExtension(extension->id());
  extension = UpdateIncreasingPermissionExtension(extension, path_v2_, 0);
  ASSERT_FALSE(GetExtensionDisabledGlobalError());
}

// Test that no error appears if the disable reason is unknown
// (but probably was by the user).
IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest,
                       UnknownReasonSamePermissions) {
  const Extension* extension = InstallIncreasingPermissionExtensionV1();
  DisableExtension(extension->id());
  // Clear disable reason to simulate legacy disables.
  service_->extension_prefs()->ClearDisableReasons(extension->id());
  // Upgrade to version 2. Infer from version 1 having the same permissions
  // granted by the user that it was disabled by the user.
  extension = UpdateIncreasingPermissionExtension(extension, path_v2_, 0);
  ASSERT_TRUE(extension);
  ASSERT_FALSE(GetExtensionDisabledGlobalError());
}

// Test that an error appears if the disable reason is unknown
// (but probably was for increased permissions).
// Disabled due to http://crbug.com/246431
IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest,
                       DISABLED_UnknownReasonHigherPermissions) {
  const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();
  // Clear disable reason to simulate legacy disables.
  service_->extension_prefs()->ClearDisableReasons(extension->id());
  // We now have version 2 but only accepted permissions for version 1.
  GlobalError* error = GetExtensionDisabledGlobalError();
  ASSERT_TRUE(error);
  // Also, remove the upgrade error for version 2.
  GlobalErrorServiceFactory::GetForProfile(browser()->profile())->
      RemoveGlobalError(error);
  delete error;
  // Upgrade to version 3, with even higher permissions. Infer from
  // version 2 having higher-than-granted permissions that it was disabled
  // for permissions increase.
  extension = UpdateIncreasingPermissionExtension(extension, path_v3_, 0);
  ASSERT_TRUE(extension);
  ASSERT_TRUE(GetExtensionDisabledGlobalError());
}

// Test that an error appears if the extension gets disabled because a
// version with higher permissions was installed by sync.
IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest,
                       HigherPermissionsFromSync) {
  // Get data for extension v2 (disabled) into sync.
  const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();
  std::string extension_id = extension->id();
  // service_->GrantPermissionsAndEnableExtension(extension, false);
  extensions::ExtensionSyncData sync_data =
      service_->GetExtensionSyncData(*extension);
  UninstallExtension(extension_id);
  extension = NULL;

  // Install extension v1.
  InstallIncreasingPermissionExtensionV1();

  // Note: This interceptor gets requests on the IO thread.
  content::URLLocalHostRequestPrepackagedInterceptor interceptor;
  net::URLFetcher::SetEnableInterceptionForTests(true);
  interceptor.SetResponseIgnoreQuery(
      GURL("http://localhost/autoupdate/updates.xml"),
      test_data_dir_.AppendASCII("permissions_increase")
                    .AppendASCII("updates.xml"));
  interceptor.SetResponseIgnoreQuery(
      GURL("http://localhost/autoupdate/v2.crx"),
      scoped_temp_dir_.path().AppendASCII("permissions2.crx"));

  extensions::ExtensionUpdater::CheckParams params;
  params.check_blacklist = false;
  service_->updater()->set_default_check_params(params);

  // Sync is replacing an older version, so it pends.
  EXPECT_FALSE(service_->ProcessExtensionSyncData(sync_data));

  WaitForExtensionInstall();
  BrowserThread::GetBlockingPool()->FlushForTesting();

  extension = service_->GetExtensionById(extension_id, true);
  ASSERT_TRUE(extension);
  EXPECT_EQ("2", extension->VersionString());
  EXPECT_EQ(1u, service_->disabled_extensions()->size());
  EXPECT_EQ(Extension::DISABLE_PERMISSIONS_INCREASE,
            service_->extension_prefs()->GetDisableReasons(extension_id));
  EXPECT_TRUE(GetExtensionDisabledGlobalError());
}
<commit_msg>Actually fix ExtensionDisabledGlobalErrorTest flakiness.<commit_after>// Copyright (c) 2012 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 "base/files/file_path.h"
#include "base/files/scoped_temp_dir.h"
#include "base/run_loop.h"
#include "base/threading/sequenced_worker_pool.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_prefs.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/updater/extension_updater.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/global_error/global_error.h"
#include "chrome/browser/ui/global_error/global_error_service.h"
#include "chrome/browser/ui/global_error/global_error_service_factory.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/extension.h"
#include "content/public/test/test_utils.h"
#include "content/test/net/url_request_prepackaged_interceptor.h"
#include "net/url_request/url_fetcher.h"

using extensions::Extension;

class ExtensionDisabledGlobalErrorTest : public ExtensionBrowserTest {
 protected:
  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    ExtensionBrowserTest::SetUpCommandLine(command_line);
    command_line->AppendSwitchASCII(switches::kAppsGalleryUpdateURL,
                                    "http://localhost/autoupdate/updates.xml");
  }

  virtual void SetUpOnMainThread() OVERRIDE {
    EXPECT_TRUE(scoped_temp_dir_.CreateUniqueTempDir());
    service_ = browser()->profile()->GetExtensionService();
    base::FilePath pem_path = test_data_dir_.
        AppendASCII("permissions_increase").AppendASCII("permissions.pem");
    path_v1_ = PackExtensionWithOptions(
        test_data_dir_.AppendASCII("permissions_increase").AppendASCII("v1"),
        scoped_temp_dir_.path().AppendASCII("permissions1.crx"),
        pem_path,
        base::FilePath());
    path_v2_ = PackExtensionWithOptions(
        test_data_dir_.AppendASCII("permissions_increase").AppendASCII("v2"),
        scoped_temp_dir_.path().AppendASCII("permissions2.crx"),
        pem_path,
        base::FilePath());
    path_v3_ = PackExtensionWithOptions(
        test_data_dir_.AppendASCII("permissions_increase").AppendASCII("v3"),
        scoped_temp_dir_.path().AppendASCII("permissions3.crx"),
        pem_path,
        base::FilePath());
  }

  // Returns the ExtensionDisabledGlobalError, if present.
  // Caution: currently only supports one error at a time.
  GlobalError* GetExtensionDisabledGlobalError() {
    return GlobalErrorServiceFactory::GetForProfile(browser()->profile())->
        GetGlobalErrorByMenuItemCommandID(IDC_EXTENSION_DISABLED_FIRST);
  }

  // Install the initial version, which should happen just fine.
  const Extension* InstallIncreasingPermissionExtensionV1() {
    size_t size_before = service_->extensions()->size();
    const Extension* extension = InstallExtension(path_v1_, 1);
    if (!extension)
      return NULL;
    if (service_->extensions()->size() != size_before + 1)
      return NULL;
    return extension;
  }

  // Upgrade to a version that wants more permissions. We should disable the
  // extension and prompt the user to reenable.
  const Extension* UpdateIncreasingPermissionExtension(
      const Extension* extension,
      const base::FilePath& crx_path,
      int expected_change) {
    size_t size_before = service_->extensions()->size();
    if (UpdateExtension(extension->id(), crx_path, expected_change))
      return NULL;
    BrowserThread::GetBlockingPool()->FlushForTesting();
    base::RunLoop().RunUntilIdle();
    EXPECT_EQ(size_before + expected_change, service_->extensions()->size());
    if (service_->disabled_extensions()->size() != 1u)
      return NULL;

    return *service_->disabled_extensions()->begin();
  }

  // Helper function to install an extension and upgrade it to a version
  // requiring additional permissions. Returns the new disabled Extension.
  const Extension* InstallAndUpdateIncreasingPermissionsExtension() {
    const Extension* extension = InstallIncreasingPermissionExtensionV1();
    extension = UpdateIncreasingPermissionExtension(extension, path_v2_, -1);
    return extension;
  }

  ExtensionService* service_;
  base::ScopedTempDir scoped_temp_dir_;
  base::FilePath path_v1_;
  base::FilePath path_v2_;
  base::FilePath path_v3_;
};

// Tests the process of updating an extension to one that requires higher
// permissions, and accepting the permissions.
IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, AcceptPermissions) {
  const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();
  ASSERT_TRUE(extension);
  ASSERT_TRUE(GetExtensionDisabledGlobalError());
  const size_t size_before = service_->extensions()->size();

  service_->GrantPermissionsAndEnableExtension(extension);
  EXPECT_EQ(size_before + 1, service_->extensions()->size());
  EXPECT_EQ(0u, service_->disabled_extensions()->size());
  ASSERT_FALSE(GetExtensionDisabledGlobalError());
}

// Tests uninstalling an extension that was disabled due to higher permissions.
IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, Uninstall) {
  const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();
  ASSERT_TRUE(extension);
  ASSERT_TRUE(GetExtensionDisabledGlobalError());
  const size_t size_before = service_->extensions()->size();

  UninstallExtension(extension->id());
  EXPECT_EQ(size_before, service_->extensions()->size());
  EXPECT_EQ(0u, service_->disabled_extensions()->size());
  ASSERT_FALSE(GetExtensionDisabledGlobalError());
}

// Tests that no error appears if the user disabled the extension.
IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, UserDisabled) {
  const Extension* extension = InstallIncreasingPermissionExtensionV1();
  DisableExtension(extension->id());
  extension = UpdateIncreasingPermissionExtension(extension, path_v2_, 0);
  ASSERT_FALSE(GetExtensionDisabledGlobalError());
}

// Test that no error appears if the disable reason is unknown
// (but probably was by the user).
IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest,
                       UnknownReasonSamePermissions) {
  const Extension* extension = InstallIncreasingPermissionExtensionV1();
  DisableExtension(extension->id());
  // Clear disable reason to simulate legacy disables.
  service_->extension_prefs()->ClearDisableReasons(extension->id());
  // Upgrade to version 2. Infer from version 1 having the same permissions
  // granted by the user that it was disabled by the user.
  extension = UpdateIncreasingPermissionExtension(extension, path_v2_, 0);
  ASSERT_TRUE(extension);
  ASSERT_FALSE(GetExtensionDisabledGlobalError());
}

// Test that an error appears if the disable reason is unknown
// (but probably was for increased permissions).
IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest,
                       UnknownReasonHigherPermissions) {
  const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();
  // Clear disable reason to simulate legacy disables.
  service_->extension_prefs()->ClearDisableReasons(extension->id());
  // We now have version 2 but only accepted permissions for version 1.
  GlobalError* error = GetExtensionDisabledGlobalError();
  ASSERT_TRUE(error);
  // Also, remove the upgrade error for version 2.
  GlobalErrorServiceFactory::GetForProfile(browser()->profile())->
      RemoveGlobalError(error);
  delete error;
  // Upgrade to version 3, with even higher permissions. Infer from
  // version 2 having higher-than-granted permissions that it was disabled
  // for permissions increase.
  extension = UpdateIncreasingPermissionExtension(extension, path_v3_, 0);
  ASSERT_TRUE(extension);
  ASSERT_TRUE(GetExtensionDisabledGlobalError());
}

// Test that an error appears if the extension gets disabled because a
// version with higher permissions was installed by sync.
IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest,
                       HigherPermissionsFromSync) {
  // Get data for extension v2 (disabled) into sync.
  const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();
  std::string extension_id = extension->id();
  extensions::ExtensionSyncData sync_data =
      service_->GetExtensionSyncData(*extension);
  UninstallExtension(extension_id);
  extension = NULL;

  // Install extension v1.
  InstallIncreasingPermissionExtensionV1();

  // Note: This interceptor gets requests on the IO thread.
  content::URLLocalHostRequestPrepackagedInterceptor interceptor;
  net::URLFetcher::SetEnableInterceptionForTests(true);
  interceptor.SetResponseIgnoreQuery(
      GURL("http://localhost/autoupdate/updates.xml"),
      test_data_dir_.AppendASCII("permissions_increase")
                    .AppendASCII("updates.xml"));
  interceptor.SetResponseIgnoreQuery(
      GURL("http://localhost/autoupdate/v2.crx"),
      scoped_temp_dir_.path().AppendASCII("permissions2.crx"));

  extensions::ExtensionUpdater::CheckParams params;
  params.check_blacklist = false;
  service_->updater()->set_default_check_params(params);

  // Sync is replacing an older version, so it pends.
  EXPECT_FALSE(service_->ProcessExtensionSyncData(sync_data));

  WaitForExtensionInstall();
  BrowserThread::GetBlockingPool()->FlushForTesting();
  base::RunLoop().RunUntilIdle();

  extension = service_->GetExtensionById(extension_id, true);
  ASSERT_TRUE(extension);
  EXPECT_EQ("2", extension->VersionString());
  EXPECT_EQ(1u, service_->disabled_extensions()->size());
  EXPECT_EQ(Extension::DISABLE_PERMISSIONS_INCREASE,
            service_->extension_prefs()->GetDisableReasons(extension_id));
  EXPECT_TRUE(GetExtensionDisabledGlobalError());
}
<|endoftext|>