text:
package com.ibm.xsp.extlib.relational.jdbc.model;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.faces.context.FacesContext;
import javax.faces.el.ValueBinding;
import javax.faces.model.DataModel;
import javax.sql.RowSet;
import javax.sql.rowset.CachedRowSet;

import com.ibm.commons.util.StringUtil;
import com.ibm.xsp.FacesExceptionEx;
import com.ibm.xsp.context.FacesContextEx;
import com.ibm.xsp.extlib.model.DataAccessorSource;
import com.ibm.xsp.extlib.relational.util.JdbcUtil;
import com.ibm.xsp.model.DataContainer;
import com.ibm.xsp.model.TabularDataSource;
import com.ibm.xsp.util.StateHolderUtil;
import com.sun.rowset.CachedRowSetImpl;

/**
 * Data source used to access JDBC enabled databases using a cached row set.
 * @author Philippe Riand
 */
public class JdbcRowSetSource extends DataAccessorSource implements TabularDataSource {

    // Service access
    private String connectionManager;
    private String connectionName;
    private String connectionUrl;
    private String sqlFile;
    private String sqlQuery;
    private String sqlTable;
    private List<SqlParameter> sqlParameters;
    private Integer maxRows;
    private Boolean showDeleted;

    private String rowSetJavaClass;

    public JdbcRowSetSource() {
    }

    @Override
    public boolean isReadonly() {
        return false;
    }

    @Override
    protected JdbcRowSetAccessor createAccessor() {
        return new JdbcRowSetAccessor(this);
    }

    @Override
    public DataModel getDataModel() {
        return new JdbcRowSetAccessorModel(this,(Container)getDataContainer());
    }

// PHIL: we assume the default id -> if the SQL change, the user must refresh the
// data source explicitly
//    @Override
//    protected String composeUniqueId() {
//      String sq = getSqlQuery();
//        if(StringUtil.isNotEmpty(sq)) {
//          return sq;
//        }
//      String sf = getSqlFile();
//        if(StringUtil.isNotEmpty(sf)) {
//          return sf;
//        }
//        return super.composeUniqueId();
//    }

    public String getConnectionManager() {
        if (null != connectionManager) {
            return connectionManager;
        }
        ValueBinding valueBinding = getValueBinding("connectionManager"); // $NON-NLS-1$
        if (valueBinding != null) {
            String value = (String)valueBinding.getValue(getFacesContext());
            return value;
        }
        return null;
    }
    public void setConnectionManager(String connectionManager) {
        this.connectionManager = connectionManager;
    }

    public String getConnectionName() {
        if (null != connectionName) {
            return connectionName;
        }
        ValueBinding valueBinding = getValueBinding("connectionName"); // $NON-NLS-1$
        if (valueBinding != null) {
            String value = (String)valueBinding.getValue(getFacesContext());
            return value;
        }
        return null;
    }
    public void setConnectionName(String connectionName) {
        this.connectionName = connectionName;
    }

    public String getConnectionUrl() {
        if (null != connectionUrl) {
            return connectionUrl;
        }
        ValueBinding valueBinding = getValueBinding("connectionUrl"); // $NON-NLS-1$
        if (valueBinding != null) {
            String value = (String)valueBinding.getValue(getFacesContext());
            return value;
        }
        return null;
    }
    public void setConnectionUrl(String connectionUrl) {
        this.connectionUrl = connectionUrl;
    }

    public String getSqlFile() {
        if (null != sqlFile) {
            return sqlFile;
        }
        ValueBinding valueBinding = getValueBinding("sqlFile"); // $NON-NLS-1$
        if (valueBinding != null) {
            String value = (String)valueBinding.getValue(getFacesContext());
            return value;
        }
        return null;
    }
    public void setSqlFile(String sqlFile) {
        this.sqlFile = sqlFile;
    }

    public String getSqlQuery() {
        if (null != sqlQuery) {
            return sqlQuery;
        }
        ValueBinding valueBinding = getValueBinding("sqlQuery"); // $NON-NLS-1$
        if (valueBinding != null) {
            String value = (String)valueBinding.getValue(getFacesContext());
            return value;
        }
        return null;
    }
    public void setSqlQuery(String sqlQuery) {
        this.sqlQuery = sqlQuery;
    }

    public String getRowSetJavaClass() {
        if (null != rowSetJavaClass) {
            return rowSetJavaClass;
        }
        ValueBinding valueBinding = getValueBinding("rowSetJavaClass"); // $NON-NLS-1$
        if (valueBinding != null) {
            String value = (String)valueBinding.getValue(getFacesContext());
            return value;
        }
        return null;
    }
    public void setRowSetJavaClass(String rowSetClass) {
        this.rowSetJavaClass = rowSetClass;
    }

    public String getSqlTable() {
        if (null != sqlTable) {
            return sqlTable;
        }
        ValueBinding valueBinding = getValueBinding("sqlTable"); // $NON-NLS-1$
        if (valueBinding != null) {
            String value = (String)valueBinding.getValue(getFacesContext());
            return value;
        }
        return null;
    }
    public void setSqlTable(String sqlTable) {
        this.sqlTable = sqlTable;
    }

    public List<SqlParameter> getSqlParameters() {
        return this.sqlParameters;
    }

    public void addSqlParameter(SqlParameter attribute) {
        if(sqlParameters==null) {
            sqlParameters = new ArrayList<SqlParameter>();
        }
        sqlParameters.add(attribute);
    }

    public void setSqlParameters(List<SqlParameter> parameters) {
        this.sqlParameters = parameters;
    }

    public int getMaxRows() {
        if (null != this.maxRows) {
            return this.maxRows;
        }
        ValueBinding _vb = getValueBinding("maxRows"); //$NON-NLS-1$
        if (_vb != null) {
            Number val = (Number) _vb.getValue(FacesContext.getCurrentInstance());
            if(val!=null) {
                return val.intValue();
            }
        }
        return 0;
    }

    public void setMaxRows(int maxRows) {
        this.maxRows = maxRows;
    }

    public boolean isShowDeleted() {
        if (null != this.showDeleted) {
            return this.showDeleted;
        }
        ValueBinding _vb = getValueBinding("showDeleted"); //$NON-NLS-1$
        if (_vb != null) {
            Boolean val = (Boolean) _vb.getValue(FacesContext.getCurrentInstance());
            if(val!=null) {
                return val;
            }
        }
        return false;
    }

    public void setShowDeleted(boolean showDeleted) {
        this.showDeleted = showDeleted;
    }

    @Override
    public Object saveState(FacesContext context) {
        if (isTransient()) {
            return null;
        }
        Object[] state = new Object[11];
        state[0] = super.saveState(context);
        state[1] = connectionManager;
        state[2] = connectionName;
        state[3] = connectionUrl;
        state[4] = sqlFile;
        state[5] = sqlQuery;
        state[6] = sqlTable;
        state[7] = rowSetJavaClass;
        state[8] = StateHolderUtil.saveList(context, sqlParameters);
        state[9] = maxRows;
        state[10] = showDeleted;
        return state;
    }
    @Override
    public void restoreState(FacesContext context, Object state) {
        Object[] values = (Object[])state;
        super.restoreState(context, values[0]);
        this.connectionManager = (String)values[1];
        this.connectionName = (String)values[2];
        this.connectionUrl = (String)values[3];
        this.sqlFile = (String)values[4];
        this.sqlQuery = (String)values[5];
        this.sqlTable = (String)values[6];
        this.rowSetJavaClass = (String)values[7];
        this.sqlParameters = StateHolderUtil.restoreList(context, getComponent(), values[8]);
        this.maxRows = (Integer)values[9];
        this.showDeleted = (Boolean)values[10];
    }

    // ===================================================================
    // JDBC related methods
    // ===================================================================

    public RowSet createRowSet() {
        try {
            RowSet rowSet = newRowSet();
            initRowSet(rowSet);
            return rowSet;
        } catch(SQLException ex) {
            throw new FacesExceptionEx(ex);
        }
    }
    protected RowSet newRowSet() throws SQLException {
        try {
            String rsClass = getRowSetJavaClass();
            if(StringUtil.isNotEmpty(rsClass)) {
                try {
                    Class<?> c = FacesContextEx.getCurrentInstance().getContextClassLoader().loadClass(rsClass);
                    return (RowSet)c.newInstance();
                } catch(Exception ex) {
                    throw new FacesExceptionEx(ex,StringUtil.format("Error while creating a RowSet object with class {0}", rsClass)); // $NLX-JdbcRowSetSource.Errorwhileinstanciating0ofclass1-1$ $NON-NLS-2$
                }
            } else {
                CachedRowSet rs = new CachedRowSetImpl();
                rs.setReadOnly(false);
                return rs;
            }
        } catch(SQLException ex) {
            throw new FacesExceptionEx(ex);
        }
    }
    protected void initRowSet(RowSet rowSet) throws SQLException {
        if(rowSet instanceof CachedRowSet) {
            CachedRowSet r = (CachedRowSet)rowSet;
            if(isShowDeleted()) {
                r.setShowDeleted(true);
            }
        }
    }

    // ===================================================================
    // JDBC related methods
    // ===================================================================

    public String findSqlQuery() {
        // Look for a table name first
        String tableName = getSqlTable();
        if(StringUtil.isNotEmpty(tableName)) {
            return StringUtil.format("SELECT * FROM {0}", tableName); // $NON-NLS-1$
        }
        // Look for the sql query property
        String sql = getSqlQuery();
        if(StringUtil.isNotEmpty(sql)) {
            return sql;
        }
        // Then look for a resource
        return JdbcUtil.readSqlFile(getSqlFile());
    }

    @Override
    public boolean save(FacesContext context, DataContainer data)
            throws FacesExceptionEx {
        JdbcRowSetAccessor ac = ((JdbcRowSetAccessorModel)getDataModel()).getDataAccessor();
        try {
            ac.acceptChanges();
        } catch (SQLException ex) {
            throw new FacesExceptionEx(ex);
        }
        return true;
    }
}


text:
package hu.advancedweb.scott.instrumentation.transformation;

import hu.advancedweb.scott.instrumentation.transformation.config.Configuration;
import hu.advancedweb.scott.instrumentation.transformation.param.InstrumentationActions;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;

import hu.advancedweb.scott.instrumentation.transformation.param.DiscoveryClassVisitor;

/**
 * Entry point for Scott's ASM based bytecode instrumentation.
 *
 * @author David Csakvari
 */
public class ScottClassTransformer {

	/**
	 * Instrument the given class based on the configuration.
	 * @param classfileBuffer class to be instrumented
	 * @param configuration configuration settings
	 * @return instrumented class
	 */
	public byte[] transform(byte[] classfileBuffer, Configuration configuration) {
		InstrumentationActions instrumentationActions = calculateTransformationParameters(classfileBuffer, configuration);
		if (!instrumentationActions.includeClass) {
			return classfileBuffer;
		}
		return transform(classfileBuffer, instrumentationActions);
	}

	/**
	 * Based on the structure of the class and the supplied configuration, determine
	 * the concrete instrumentation actions for the class.
	 * @param classfileBuffer class to be analyzed
	 * @param configuration configuration settings
	 * @return instrumentation actions to be applied
	 */
	private InstrumentationActions calculateTransformationParameters(byte[] classfileBuffer, Configuration configuration) {
		DiscoveryClassVisitor discoveryClassVisitor = new DiscoveryClassVisitor(configuration);
		new ClassReader(classfileBuffer).accept(discoveryClassVisitor, 0);
		return discoveryClassVisitor.getTransformationParameters().build();
	}

	/**
	 * Perform the given instrumentation actions on a class.
	 * @param classfileBuffer class to be transformed
	 * @param instrumentationActions instrumentation actions to be applied
	 * @return instrumented class
	 */
	private byte[] transform(byte[] classfileBuffer, InstrumentationActions instrumentationActions) {
		ClassReader classReader = new ClassReader(classfileBuffer);
		ClassWriter classWriter = new ClassWriter(classReader, ClassWriter.COMPUTE_FRAMES);
		ClassVisitor localVariableStateEmitterTestClassVisitor = new StateTrackingClassVisitor(classWriter,
				instrumentationActions);
		classReader.accept(localVariableStateEmitterTestClassVisitor, 0);
		return classWriter.toByteArray();
	}

}

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'
module Finitio
  describe MultiRelationType, "equality" do

    let(:h1){ Heading.new([Attribute.new(:r, intType), Attribute.new(:b, intType, false)]) }
    let(:h2){ Heading.new([Attribute.new(:b, intType, false), Attribute.new(:r, intType)]) }
    let(:h3){ Heading.new([Attribute.new(:b, intType)])                             }
    let(:h4){ Heading.new([Attribute.new(:b, intType), Attribute.new(:r, intType)]) }

    let(:type1)  { MultiRelationType.new(h1) }
    let(:type2)  { MultiRelationType.new(h2) }
    let(:type3)  { MultiRelationType.new(h3) }
    let(:type4)  { MultiRelationType.new(h4) }

    it 'should apply structural equality' do
      expect(type1 == type2).to eq(true)
      expect(type2 == type1).to eq(true)
    end

    it 'should apply distinguish different types' do
      expect(type1 == type3).to eq(false)
      expect(type2 == type3).to eq(false)
      expect(type1 == type4).to eq(false)
    end

    it 'should be a total function, with false for non types' do
      expect(type1 == 12).to eq(false)
    end

    it 'should implement hash accordingly' do
      expect([type1, type2].map(&:hash).uniq.size).to eq(1)
      expect(type1.hash).not_to eq(type4.hash)
    end

  end
end


text:
#ifndef _SYS_SELECT_H_
#define _SYS_SELECT_H_

#include <sys/types.h>

/*
 * Select uses bit masks of file descriptors in longs.
 * These macros manipulate such bit fields (the filesystem macros use chars).
 * FD_SETSIZE may be defined by the user, but the default here
 * should be >= NOFILE (param.h).
 */
#ifndef FD_SETSIZE
#define FD_SETSIZE  32
#endif

typedef long fd_mask;
#define NFDBITS     (sizeof(fd_mask) * NBBY)    /* bits per mask */

typedef struct fd_set {
    fd_mask fds_bits[1];
} fd_set;

#define FD_SET(n, p)    ((p)->fds_bits[(n)/NFDBITS] |= (1L << ((n) % NFDBITS)))
#define FD_CLR(n, p)    ((p)->fds_bits[(n)/NFDBITS] &= ~(1L << ((n) % NFDBITS)))
#define FD_ISSET(n, p)  ((p)->fds_bits[(n)/NFDBITS] & (1L << ((n) % NFDBITS)))
#define FD_ZERO(p)      bzero((char *)(p), sizeof(*(p)))

#ifndef KERNEL
#ifndef CROSS
void     bzero(void *, unsigned long);
#endif

/* According to POSIX.1-2001 */
struct timeval;
int select (int nfds, fd_set *readfds, fd_set *writefds,
        fd_set *exceptfds, struct timeval *timeout);

#endif /* !KERNEL */

#endif /* !_SYS_SELECT_H_ */


text:
package app.arsh.omniknightapp;

import app.arsh.omniknightapp.presenter.MainActivityPresenter;
import app.arsh.omniknightapp.presenter.interfaces.MainActivityInterface;
import app.arsh.omniknightapp.view.activities.MainActivity;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

import static org.mockito.Mockito.verify;

/**
 * Created by arash on 1/3/17.
 */

@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 23, manifest = "/src/main/AndroidManifest.xml")
public class MainActivityPresenterUnitTest {

  MainActivityInterface mainActivityInterface;
  MainActivity mainActivity;
  private MainActivityPresenter presenter;

  @Test
  public void testConstructor() {
    mainActivityInterface = Mockito.mock(MainActivityInterface.class);
    mainActivity = Robolectric.setupActivity(MainActivity.class);
    presenter = new MainActivityPresenter(mainActivityInterface, mainActivity);

    presenter.onCreateViewFinished();
    if (presenter.getDbClient().getCountries().size() == 0) verify(mainActivityInterface).loadNoCityView();
    else verify(mainActivityInterface).loadCities(presenter.getDbClient().getCountries());
  }

  @Test
  public void fabButtonClickedEvent() {
    mainActivityInterface = Mockito.mock(MainActivityInterface.class);
    mainActivity = Robolectric.setupActivity(MainActivity.class);

    presenter = new MainActivityPresenter(mainActivityInterface, mainActivity);

    mainActivity.findViewById(R.id.fab).performClick();
    presenter.fabButtonClicked();
    verify(mainActivityInterface).loadCountrySelectionFragment();

  }
}


text:
a mongoose plugin adding owner_id to model instance and findByIdAndOwnerId static methods

## Install
Install the module with:

```bash
npm install mongoose-ownable
```

## Usage
```javascript
var ownable = require('mongoose-ownable');

var TestSchema = new Schema({});

TestSchema.plugin(ownable);

TestModel = mongoose.model("Test", TestSchema);

```

## License
Copyright (c) 2014 yi
Licensed under the MIT license.


text:
layout: post
title: "IntelliJ Rust Changelog #171"
date: 2022-05-30 13:00:00 +0300
---

This is the last release that supports the 2021.3 IDEs. To receive plugin updates further, please upgrade
your IDE to 2022.1.

## New Features

* [#8839] Provide builds for 2022.2 major release

* [#8828] Implement [unsized coercion](https://doc.rust-lang.org/reference/type-coercions.html#unsized-coercions) in type inference engine. In particular, this fixes false-positive errors like type mismatch between `Box<[u8]>` and `Box<[u8; 4]>`

## Fixes

* [#8835] Type inference improvements:
  * Infer closure parameters types when a closure is assigned to a variable and parameters types should be inferred later
  * Fix `?` operator with `Try` trait. The (unstable) `Try` trait was moved to `core::ops::try_trait::Try` and its associated types was renamed. Now `?` works for `Poll<Result>`, for example.
  * Fix for loop over type parameter implementing `Iterator`
  * Derive recently added unstable `Destruct` trait for all types. It is used as a trait bound in stdlib

* [#8776] Take into account line breaks when showing `rustfmt` error messages

Full set of changes can be found [here](https://github.com/intellij-rust/intellij-rust/milestone/79?closed=1)

[#8776]: https://github.com/intellij-rust/intellij-rust/pull/8776
[#8828]: https://github.com/intellij-rust/intellij-rust/pull/8828
[#8835]: https://github.com/intellij-rust/intellij-rust/pull/8835
[#8839]: https://github.com/intellij-rust/intellij-rust/pull/8839


text:
'''
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you 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.
'''
import json
import os
from ambari_commons import subprocess32
import select

from mock.mock import patch
from mock.mock import MagicMock
from stacks.utils.RMFTestCase import *
from mock.mock import patch, MagicMock
from resource_management.core.base import Resource
from resource_management.core.exceptions import Fail
from resource_management.libraries.script import Script

OLD_VERSION_STUB = '2.1.0.0-400'
VERSION_STUB_WITHOUT_BUILD_NUMBER = '2.2.0.1'
VERSION_STUB = '2.2.0.1-885'

from only_for_platform import get_platform, not_for_platform, only_for_platform, os_distro_value, PLATFORM_WINDOWS

if get_platform() != PLATFORM_WINDOWS:
  import pty

subproc_mock = MagicMock()
subproc_mock.return_value = MagicMock()
subproc_stdout = MagicMock()
subproc_mock.return_value.stdout = subproc_stdout

@not_for_platform(PLATFORM_WINDOWS)
@patch.object(os, "read", new=MagicMock(return_value=None))
@patch.object(select, "select", new=MagicMock(return_value=([subproc_stdout], None, None)))
@patch("pty.openpty", new = MagicMock(return_value=(1,5)))
@patch.object(os, "close", new=MagicMock())
@patch.object(subprocess32, "Popen", new=subproc_mock)
class TestInstallPackages(RMFTestCase):

  def setUp(self):
    self.maxDiff = None

  @staticmethod
  def _add_packages(*args):
    return [
      ["pkg1", "1.0", "repo"],
      ["pkg2", "2.0", "repo2"]
    ]

  @staticmethod
  def _add_packages_available(*args):
    return [
      ["hadoop_2_2_0_1_885", "1.0", "HDP-2.2"],
      ["hadooplzo_2_2_0_1_885", "1.0", "HDP-2.2"],
      ["hadoop_2_2_0_1_885-libhdfs", "1.0", "HDP-2.2"]
    ]

  @staticmethod
  def _add_packages_lookUpYum(*args):
    return TestInstallPackages._add_packages_available(*args)

  def test_get_installed_package_version(self):
    from resource_management.core.providers.package.yumrpm import YumProvider

    provider = YumProvider(None)
    with patch.object(provider, "checked_call") as checked_call_mock:
      checked_call_mock.return_value = 0, "3.1.0.0-54.el7.centos"
      expected_version = provider.get_installed_package_version("test")
      self.assertEquals("3.1.0.0-54", expected_version)

  @patch("resource_management.libraries.functions.list_ambari_managed_repos.list_ambari_managed_repos")
  @patch("resource_management.core.providers.get_provider")
  @patch("resource_management.libraries.script.Script.put_structured_out")
  @patch("resource_management.libraries.functions.stack_select.get_stack_versions")
  @patch("resource_management.libraries.functions.repo_version_history.read_actual_version_from_history_file")
  @patch("resource_management.libraries.functions.repo_version_history.write_actual_version_to_history_file")
  @patch("ambari_commons.shell.subprocess_with_timeout")
  def test_normal_flow_rhel(self,
                            subprocess_with_timeout,
                            write_actual_version_to_history_file_mock,
                            read_actual_version_from_history_file_mock,
                            stack_versions_mock,
                            put_structured_out_mock,
                            get_provider, list_ambari_managed_repos_mock):
    stack_versions_mock.side_effect = [
      [],  # before installation attempt
      [VERSION_STUB]
    ]
    from resource_management.core.providers.package.yumrpm import YumProvider
    provider = YumProvider(None)
    with patch.object(provider, "_lookup_packages") as lookup_packages:
      lookup_packages.side_effect = TestInstallPackages._add_packages_lookUpYum
      get_provider.return_value = provider
      list_ambari_managed_repos_mock.return_value=[]
      repo_file_name = 'ambari-hdp-1'
      use_repos = { 'HDP-UTILS-1.1.0.20': repo_file_name, 'HDP-2.2': repo_file_name }
      self.executeScript("scripts/install_packages.py",
                         classname="InstallPackages",
                         command="actionexecute",
                         config_file="install_packages_config.json",
                         target=RMFTestCase.TARGET_CUSTOM_ACTIONS,
                         os_type=('Redhat', '6.4', 'Final'),
      )
      self.assertTrue(put_structured_out_mock.called)
      self.assertEquals(put_structured_out_mock.call_args[0][0],
                        {'package_installation_result': 'SUCCESS',
                         'repository_version_id': 1,
                         'actual_version': VERSION_STUB})
      self.assertResourceCalled('Repository', 'HDP-UTILS-1.1.0.20',
                                base_url=u'http://repo1/HDP/centos5/2.x/updates/2.2.0.0',
                                action=['create'],
                                components=[u'HDP-UTILS', 'main'],
                                repo_template='[{{repo_id}}]\nname={{repo_id}}\n{% if mirror_list %}mirrorlist={{mirror_list}}{% else %}baseurl={{base_url}}{% endif %}\n\npath=/\nenabled=1\ngpgcheck=0',
                                repo_file_name=repo_file_name,
                                mirror_list=None,
                                append_to_file=False,
      )
      self.assertResourceCalled('Repository', 'HDP-2.2',
                                base_url=u'http://repo1/HDP/centos5/2.x/updates/2.2.0.0',
                                action=['create'],
                                components=[u'HDP', 'main'],
                                repo_template='[{{repo_id}}]\nname={{repo_id}}\n{% if mirror_list %}mirrorlist={{mirror_list}}{% else %}baseurl={{base_url}}{% endif %}\n\npath=/\nenabled=1\ngpgcheck=0',
                                repo_file_name=repo_file_name,
                                mirror_list=None,
                                append_to_file=True,
      )
      self.assertResourceCalled('Package', 'hdp-select', action=["upgrade"], use_repos=use_repos, retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'hadoop_2_2_0_1_885', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'snappy', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'snappy-devel', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'lzo', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'hadooplzo_2_2_0_1_885', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'hadoop_2_2_0_1_885-libhdfs', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'ambari-log4j', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertNoMoreResources()

  @patch("resource_management.core.providers.get_provider")
  @patch("resource_management.libraries.script.Script.put_structured_out")
  @patch("resource_management.libraries.functions.stack_select.get_stack_versions")
  @patch("resource_management.libraries.functions.repo_version_history.read_actual_version_from_history_file")
  @patch("resource_management.libraries.functions.repo_version_history.write_actual_version_to_history_file")
  @patch("ambari_commons.shell.subprocess_with_timeout")
  def test_no_repos(self,
                            subprocess_with_timeout,
                            write_actual_version_to_history_file_mock,
                            read_actual_version_from_history_file_mock,
                            stack_versions_mock,
                            put_structured_out_mock, get_provider):
    stack_versions_mock.side_effect = [
      [],  # before installation attempt
      [VERSION_STUB]
    ]

    config_file = self.get_src_folder() + "/test/python/custom_actions/configs/install_packages_config.json"
    with open(config_file, "r") as f:
      command_json = json.load(f)

    command_json['repositoryFile']['repositories'] = []

    from resource_management.core.providers.package.yumrpm import YumProvider
    provider = YumProvider(None)
    with patch.object(provider, "_lookup_packages") as lookup_packages:
      lookup_packages.side_effect = TestInstallPackages._add_packages_available
      get_provider.return_value = provider
      self.executeScript("scripts/install_packages.py",
                         classname="InstallPackages",
                         command="actionexecute",
                         config_dict = command_json,
                         target=RMFTestCase.TARGET_CUSTOM_ACTIONS,
                         os_type=('Redhat', '6.4', 'Final'),
      )
      self.assertTrue(put_structured_out_mock.called)
      self.assertEquals(put_structured_out_mock.call_args[0][0],
                        {'package_installation_result': 'SUCCESS',
                         'repository_version_id': 1,
                         'actual_version': VERSION_STUB})

      self.assertResourceCalled('Package', 'hdp-select', action=["upgrade"], use_repos={}, retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', None, action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'snappy', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'snappy-devel', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'lzo', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', None, action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', None, action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'ambari-log4j', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertNoMoreResources()

  @patch("ambari_commons.os_check.OSCheck.is_suse_family")
  @patch("resource_management.libraries.functions.list_ambari_managed_repos.list_ambari_managed_repos")
  @patch("resource_management.core.providers.get_provider")
  @patch("resource_management.libraries.script.Script.put_structured_out")
  @patch("resource_management.libraries.functions.stack_select.get_stack_versions")
  @patch("resource_management.libraries.functions.repo_version_history.read_actual_version_from_history_file")
  @patch("resource_management.libraries.functions.repo_version_history.write_actual_version_to_history_file")
  @patch("ambari_commons.shell.subprocess_with_timeout")
  def test_normal_flow_sles(self, subprocess_with_timeout, write_actual_version_to_history_file_mock,
                            read_actual_version_from_history_file_mock,
                            stack_versions_mock, put_structured_out_mock,
                            get_provider, list_ambari_managed_repos_mock, is_suse_family_mock):
    is_suse_family_mock = True
    Script.stack_version_from_distro_select = VERSION_STUB
    stack_versions_mock.side_effect = [
      [],  # before installation attempt
      [VERSION_STUB]
    ]
    from resource_management.core.providers.package.yumrpm import YumProvider
    provider = YumProvider(None)
    with patch.object(provider, "_lookup_packages") as lookup_packages:
      lookup_packages.side_effect = TestInstallPackages._add_packages_available
      get_provider.return_value = provider
      list_ambari_managed_repos_mock.return_value=[]
      repo_file_name = 'ambari-hdp-1'
      use_repos = { 'HDP-UTILS-1.1.0.20': repo_file_name, 'HDP-2.2': repo_file_name }
      self.executeScript("scripts/install_packages.py",
                         classname="InstallPackages",
                         command="actionexecute",
                         config_file="install_packages_config.json",
                         target=RMFTestCase.TARGET_CUSTOM_ACTIONS,
                         os_type=('Suse', '11', 'SP1'),
                         )
      self.assertTrue(put_structured_out_mock.called)
      self.assertEquals(put_structured_out_mock.call_args[0][0],
                        {'package_installation_result': 'SUCCESS',
                         'repository_version_id': 1,
                         'actual_version': VERSION_STUB})
      self.assertResourceCalled('Repository', 'HDP-UTILS-1.1.0.20',
                                base_url=u'http://repo1/HDP/centos5/2.x/updates/2.2.0.0',
                                action=['create'],
                                components=[u'HDP-UTILS', 'main'],
                                repo_template='[{{repo_id}}]\nname={{repo_id}}\n{% if mirror_list %}mirrorlist={{mirror_list}}{% else %}baseurl={{base_url}}{% endif %}\n\npath=/\nenabled=1\ngpgcheck=0',
                                repo_file_name=repo_file_name,
                                mirror_list=None,
                                append_to_file=False,
                                )
      self.assertResourceCalled('Repository', 'HDP-2.2',
                                base_url=u'http://repo1/HDP/centos5/2.x/updates/2.2.0.0',
                                action=['create'],
                                components=[u'HDP', 'main'],
                                repo_template=u'[{{repo_id}}]\nname={{repo_id}}\n{% if mirror_list %}mirrorlist={{mirror_list}}{% else %}baseurl={{base_url}}{% endif %}\n\npath=/\nenabled=1\ngpgcheck=0',
                                repo_file_name=repo_file_name,
                                mirror_list=None,
                                append_to_file=True,
                                )
      self.assertResourceCalled('Package', 'hdp-select', action=["upgrade"], use_repos=use_repos, retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'hadoop_2_2_0_1_885', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'snappy', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'snappy-devel', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'lzo', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'hadooplzo_2_2_0_1_885', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'hadoop_2_2_0_1_885-libhdfs', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'ambari-log4j', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertNoMoreResources()

  @patch("resource_management.libraries.functions.list_ambari_managed_repos.list_ambari_managed_repos")
  @patch("ambari_commons.os_check.OSCheck.is_redhat_family")
  @patch("resource_management.libraries.script.Script.put_structured_out")
  @patch("resource_management.core.providers.get_provider")
  @patch("resource_management.libraries.functions.stack_select.get_stack_versions")
  @patch("resource_management.libraries.functions.repo_version_history.read_actual_version_from_history_file")
  @patch("resource_management.libraries.functions.repo_version_history.write_actual_version_to_history_file")
  @patch("ambari_commons.shell.subprocess_with_timeout")
  def test_exclude_existing_repo(self, subprocess_with_timeout, write_actual_version_to_history_file_mock,
                                 read_actual_version_from_history_file_mock,
                                 stack_versions_mock,
                                 get_provider, put_structured_out_mock,
                                 is_redhat_family_mock, list_ambari_managed_repos_mock):
    stack_versions_mock.side_effect = [
      [],  # before installation attempt
      [VERSION_STUB]
    ]
    Script.stack_version_from_distro_select = VERSION_STUB
    from resource_management.core.providers.package.yumrpm import YumProvider
    provider = YumProvider(None)
    with patch.object(provider, "_lookup_packages") as lookup_packages:
      lookup_packages.side_effect = TestInstallPackages._add_packages_lookUpYum
      get_provider.return_value = provider
      list_ambari_managed_repos_mock.return_value=["HDP-UTILS-2.2.0.1-885"]
      is_redhat_family_mock.return_value = True
      repo_file_name = 'ambari-hdp-1'
      use_repos = { 'HDP-UTILS-1.1.0.20': repo_file_name, 'HDP-2.2': repo_file_name }
      self.executeScript("scripts/install_packages.py",
                         classname="InstallPackages",
                         command="actionexecute",
                         config_file="install_packages_config.json",
                         target=RMFTestCase.TARGET_CUSTOM_ACTIONS,
                         os_type=('Redhat', '6.4', 'Final'),
      )
      self.assertTrue(put_structured_out_mock.called)
      self.assertEquals(put_structured_out_mock.call_args[0][0],
                        {'package_installation_result': 'SUCCESS',
                         'repository_version_id': 1,
                         'actual_version': VERSION_STUB})
      self.assertResourceCalled('Repository', 'HDP-UTILS-1.1.0.20',
                                base_url=u'http://repo1/HDP/centos5/2.x/updates/2.2.0.0',
                                action=['create'],
                                components=[u'HDP-UTILS', 'main'],
                                repo_template=u'[{{repo_id}}]\nname={{repo_id}}\n{% if mirror_list %}mirrorlist={{mirror_list}}{% else %}baseurl={{base_url}}{% endif %}\n\npath=/\nenabled=1\ngpgcheck=0',
                                repo_file_name=repo_file_name,
                                mirror_list=None,
                                append_to_file=False,
      )
      self.assertResourceCalled('Repository', 'HDP-2.2',
                                base_url='http://repo1/HDP/centos5/2.x/updates/2.2.0.0',
                                action=['create'],
                                components=[u'HDP', 'main'],
                                repo_template=u'[{{repo_id}}]\nname={{repo_id}}\n{% if mirror_list %}mirrorlist={{mirror_list}}{% else %}baseurl={{base_url}}{% endif %}\n\npath=/\nenabled=1\ngpgcheck=0',
                                repo_file_name=repo_file_name,
                                mirror_list=None,
                                append_to_file=True,
      )
      self.assertResourceCalled('Package', 'hdp-select', action=["upgrade"], use_repos=use_repos, retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'hadoop_2_2_0_1_885', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'snappy', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'snappy-devel', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'lzo', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'hadooplzo_2_2_0_1_885', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'hadoop_2_2_0_1_885-libhdfs', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'ambari-log4j', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertNoMoreResources()

  _install_failed = False

  @staticmethod
  def _add_packages_with_fail():
    arg = []
    arg.append(["pkg1_2_2_0_1_885_pack", "1.0", "repo"])
    arg.append(["pkg2_2_2_0_1_885_pack2", "2.0", "repo2"])
    if TestInstallPackages._install_failed:
      arg.append(["should_not_be_removed_pkg1", "1.0", "repo"])
      arg.append(["hadoop_2_2_0_1_885fake_pkg", "1.0", "repo"])
      arg.append(["snappy__2_2_0_1_885_fake_pkg", "3.0", "repo2"])
      arg.append(["ubuntu-like-2-2-0-1-885-fake-pkg", "3.0", "repo2"])
      arg.append(["should_not_be_removed_pkg2", "3.0", "repo2"])

    return arg

  @staticmethod
  def _new_with_exception(cls, name, env=None, provider=None, **kwargs):
    if (name != "snappy-devel"):
      return Resource.__new__(cls, name, env, provider, **kwargs)
    else:
      TestInstallPackages._install_failed = True
      raise Exception()

  @patch("resource_management.libraries.functions.list_ambari_managed_repos.list_ambari_managed_repos")
  @patch("ambari_commons.os_check.OSCheck.is_redhat_family")
  @patch("resource_management.core.providers.get_provider")
  @patch("resource_management.core.resources.packaging.Package.__new__")
  @patch("resource_management.libraries.script.Script.put_structured_out")
  @patch("ambari_commons.shell.subprocess_with_timeout")
  def test_fail(self, subprocess_with_timeout, put_structured_out_mock, Package__mock, get_provider,
                is_redhat_family_mock, list_ambari_managed_repos_mock):
    from resource_management.core.providers.package.yumrpm import YumProvider
    provider = YumProvider(None)
    with patch.object(provider, "_lookup_packages") as lookup_packages:
      lookup_packages.side_effect = TestInstallPackages._add_packages_with_fail
      is_redhat_family_mock.return_value = True
      list_ambari_managed_repos_mock.return_value = []

      def side_effect(retcode):
        TestInstallPackages._install_failed = True
        raise Exception()

      Package__mock.side_effect = side_effect
      self.assertRaises(Fail, self.executeScript, "scripts/install_packages.py",
                        classname="InstallPackages",
                        command="actionexecute",
                        config_file="install_packages_config.json",
                        target=RMFTestCase.TARGET_CUSTOM_ACTIONS,
                        os_type=('Redhat', '6.4', 'Final'))

      self.assertTrue(put_structured_out_mock.called)
      self.assertEquals(put_structured_out_mock.call_args[0][0],
                        {'repository_version_id': 1,
                        'package_installation_result': 'FAIL'})
      self.assertResourceCalled('Repository', 'HDP-UTILS-1.1.0.20',
                                base_url=u'http://repo1/HDP/centos5/2.x/updates/2.2.0.0',
                                action=['create'],
                                components=[u'HDP-UTILS', 'main'],
                                repo_template=u'[{{repo_id}}]\nname={{repo_id}}\n{% if mirror_list %}mirrorlist={{mirror_list}}{% else %}baseurl={{base_url}}{% endif %}\n\npath=/\nenabled=1\ngpgcheck=0',
                                repo_file_name=u'ambari-hdp-1',
                                mirror_list=None,
                                append_to_file=False,
                                )
      self.assertResourceCalled('Repository', 'HDP-2.2',
                                base_url=u'http://repo1/HDP/centos5/2.x/updates/2.2.0.0',
                                action=['create'],
                                components=[u'HDP', 'main'],
                                repo_template=u'[{{repo_id}}]\nname={{repo_id}}\n{% if mirror_list %}mirrorlist={{mirror_list}}{% else %}baseurl={{base_url}}{% endif %}\n\npath=/\nenabled=1\ngpgcheck=0',
                                repo_file_name=u'ambari-hdp-1',
                                mirror_list=None,
                                append_to_file=True,
                                )
      self.assertNoMoreResources()

      TestInstallPackages._install_failed = False

  @patch("ambari_commons.os_check.OSCheck.is_suse_family")
  @patch("resource_management.core.resources.packaging.Package")
  @patch("resource_management.libraries.script.Script.put_structured_out")
  @patch("resource_management.core.providers.get_provider")
  @patch("resource_management.libraries.functions.stack_select.get_stack_versions")
  @patch("resource_management.libraries.functions.repo_version_history.read_actual_version_from_history_file")
  @patch("resource_management.libraries.functions.repo_version_history.write_actual_version_to_history_file")
  @patch("ambari_commons.shell.subprocess_with_timeout")
  def test_format_package_name(self, subprocess_with_timeout, write_actual_version_to_history_file_mock,
                               read_actual_version_from_history_file_mock,
                               stack_versions_mock,
                               get_provider, put_structured_out_mock,
                               package_mock, is_suse_family_mock):
    Script.stack_version_from_distro_select = VERSION_STUB
    stack_versions_mock.side_effect = [
      [],  # before installation attempt
      [VERSION_STUB]
    ]
    read_actual_version_from_history_file_mock.return_value = VERSION_STUB
    from resource_management.core.providers.package.yumrpm import YumProvider
    provider = YumProvider(None)
    with patch.object(provider, "_lookup_packages") as lookup_packages:
      lookup_packages.side_effect = TestInstallPackages._add_packages_available

      get_provider.return_value = provider
      is_suse_family_mock.return_value = True
      repo_file_name = 'ambari-hdp-1'
      use_repos = { 'HDP-UTILS-1.1.0.20': repo_file_name, 'HDP-2.2': repo_file_name }
      self.executeScript("scripts/install_packages.py",
                         classname="InstallPackages",
                         command="actionexecute",
                         config_file="install_packages_config.json",
                         target=RMFTestCase.TARGET_CUSTOM_ACTIONS,
                         os_type=('Suse', '11', 'Final'),
                         )
      self.assertTrue(put_structured_out_mock.called)
      self.assertEquals(put_structured_out_mock.call_args[0][0],
                        {'package_installation_result': 'SUCCESS',
                         'repository_version_id': 1,
                         'actual_version': VERSION_STUB})
      self.assertResourceCalled('Repository', 'HDP-UTILS-1.1.0.20',
                                base_url=u'http://repo1/HDP/centos5/2.x/updates/2.2.0.0',
                                action=['create'],
                                components=[u'HDP-UTILS', 'main'],
                                repo_template=u'[{{repo_id}}]\nname={{repo_id}}\n{% if mirror_list %}mirrorlist={{mirror_list}}{% else %}baseurl={{base_url}}{% endif %}\n\npath=/\nenabled=1\ngpgcheck=0',
                                repo_file_name=repo_file_name,
                                mirror_list=None,
                                append_to_file=False,
                                )
      self.assertResourceCalled('Repository', 'HDP-2.2',
                                base_url=u'http://repo1/HDP/centos5/2.x/updates/2.2.0.0',
                                action=['create'],
                                components=[u'HDP', 'main'],
                                repo_template=u'[{{repo_id}}]\nname={{repo_id}}\n{% if mirror_list %}mirrorlist={{mirror_list}}{% else %}baseurl={{base_url}}{% endif %}\n\npath=/\nenabled=1\ngpgcheck=0',
                                repo_file_name=repo_file_name,
                                mirror_list=None,
                                append_to_file=True,
                                )
      self.assertResourceCalled('Package', 'hdp-select', action=["upgrade"], use_repos=use_repos, retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'hadoop_2_2_0_1_885', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'snappy', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'snappy-devel', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'lzo', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'hadooplzo_2_2_0_1_885', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'hadoop_2_2_0_1_885-libhdfs', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'ambari-log4j', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertNoMoreResources()

  @patch("ambari_commons.os_check.OSCheck.is_suse_family")
  @patch("resource_management.core.resources.packaging.Package")
  @patch("resource_management.libraries.script.Script.put_structured_out")
  @patch("resource_management.core.providers.get_provider")
  @patch("resource_management.libraries.functions.stack_select.get_stack_versions")
  @patch("resource_management.libraries.functions.repo_version_history.read_actual_version_from_history_file")
  @patch("resource_management.libraries.functions.repo_version_history.write_actual_version_to_history_file")
  @patch("ambari_commons.shell.subprocess_with_timeout")
  def test_format_package_name_via_repositoryFile(self, subprocess_with_timeout, write_actual_version_to_history_file_mock,
                                                  read_actual_version_from_history_file_mock,
                                                  stack_versions_mock,
                                                  get_provider, put_structured_out_mock,
                                                  package_mock, is_suse_family_mock):
    Script.stack_version_from_distro_select = VERSION_STUB
    stack_versions_mock.side_effect = [
      [],  # before installation attempt
      [VERSION_STUB]
    ]
    read_actual_version_from_history_file_mock.return_value = VERSION_STUB
    from resource_management.core.providers.package.yumrpm import YumProvider
    provider = YumProvider(None)
    with patch.object(provider, "_lookup_packages") as lookup_packages:
      lookup_packages.side_effect = TestInstallPackages._add_packages_available
      get_provider.return_value = provider
      is_suse_family_mock.return_value = True

      config_file = self.get_src_folder() + "/test/python/custom_actions/configs/install_packages_repository_file.json"
      with open(config_file, "r") as f:
        command_json = json.load(f)

      command_json['repositoryFile']['repoVersion'] = '2.2.0.1-990'

      repo_file_name = 'ambari-hdp-4'
      use_repos = { 'HDP-UTILS-1.1.0.20-repo-4': repo_file_name, 'HDP-2.2-repo-4': repo_file_name }
      self.executeScript("scripts/install_packages.py",
                         classname="InstallPackages",
                         command="actionexecute",
                         config_dict=command_json,
                         target=RMFTestCase.TARGET_CUSTOM_ACTIONS,
                         os_type=('Suse', '11', 'Final'),
                         )
      self.assertTrue(put_structured_out_mock.called)
      self.assertEquals(put_structured_out_mock.call_args[0][0],
                        {'package_installation_result': 'SUCCESS',
                         'repository_version_id': 4,
                         'actual_version': VERSION_STUB})
      self.assertResourceCalled('Repository', 'HDP-UTILS-1.1.0.20-repo-4',
                                base_url=u'http://repo1/HDP-UTILS/centos5/2.x/updates/2.2.0.0',
                                action=['create'],
                                components=[u'HDP-UTILS', 'main'],
                                repo_template=u'[{{repo_id}}]\nname={{repo_id}}\n{% if mirror_list %}mirrorlist={{mirror_list}}{% else %}baseurl={{base_url}}{% endif %}\n\npath=/\nenabled=1\ngpgcheck=0',
                                repo_file_name=repo_file_name,
                                mirror_list=None,
                                append_to_file=False,
                                )
      self.assertResourceCalled('Repository', 'HDP-2.2-repo-4',
                                base_url=u'http://repo1/HDP/centos5/2.x/updates/2.2.0.0',
                                action=['create'],
                                components=[u'HDP', 'main'],
                                repo_template=u'[{{repo_id}}]\nname={{repo_id}}\n{% if mirror_list %}mirrorlist={{mirror_list}}{% else %}baseurl={{base_url}}{% endif %}\n\npath=/\nenabled=1\ngpgcheck=0',
                                repo_file_name=repo_file_name,
                                mirror_list=None,
                                append_to_file=True,
                                )
      self.assertResourceCalled('Package', 'hdp-select', action=["upgrade"], use_repos=use_repos, retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'hadoop_2_2_0_1_885', action=["upgrade"], retry_count=5,
                                retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'snappy', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'snappy-devel', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'lzo', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'hadooplzo_2_2_0_1_885', action=["upgrade"], retry_count=5,
                                retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'hadoop_2_2_0_1_885-libhdfs', action=["upgrade"], retry_count=5,
                                retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'ambari-log4j', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertNoMoreResources()

  @patch("resource_management.libraries.functions.list_ambari_managed_repos.list_ambari_managed_repos")
  @patch("resource_management.core.providers.get_provider")
  @patch("resource_management.libraries.script.Script.put_structured_out")
  @patch("resource_management.libraries.functions.stack_select.get_stack_versions")
  @patch("resource_management.libraries.functions.repo_version_history.read_actual_version_from_history_file")
  @patch("resource_management.libraries.functions.repo_version_history.write_actual_version_to_history_file")
  @patch("ambari_commons.shell.subprocess_with_timeout")
  def test_version_reporting__build_number_defined(self, subprocess_with_timeout,
                                                         write_actual_version_to_history_file_mock,
                                                         read_actual_version_from_history_file_mock,
                                                         stack_versions_mock,
                                                         put_structured_out_mock, get_provider, list_ambari_managed_repos_mock):
    stack_versions_mock.side_effect = [
      [OLD_VERSION_STUB],  # before installation attempt
      [OLD_VERSION_STUB, VERSION_STUB]
    ]

    config_file = self.get_src_folder() + "/test/python/custom_actions/configs/install_packages_config.json"
    with open(config_file, "r") as f:
      command_json = json.load(f)

    command_json['repositoryFile']['repoVersion'] = VERSION_STUB

    from resource_management.core.providers.package.yumrpm import YumProvider
    provider = YumProvider(None)
    with patch.object(provider, "_lookup_packages") as lookup_packages:
      lookup_packages.side_effect = TestInstallPackages._add_packages_available
      get_provider.return_value = provider
      list_ambari_managed_repos_mock.return_value = []
      self.executeScript("scripts/install_packages.py",
                         classname="InstallPackages",
                         command="actionexecute",
                         config_dict=command_json,
                         target=RMFTestCase.TARGET_CUSTOM_ACTIONS,
                         os_type=('Redhat', '6.4', 'Final'),
                         )
      self.assertTrue(put_structured_out_mock.called)
      self.assertEquals(put_structured_out_mock.call_args[0][0],
                        {'package_installation_result': 'SUCCESS',
                         'repository_version_id': 1,
                         'actual_version': VERSION_STUB})
      self.assertTrue(write_actual_version_to_history_file_mock.called)
      self.assertEquals(write_actual_version_to_history_file_mock.call_args[0], (VERSION_STUB_WITHOUT_BUILD_NUMBER, VERSION_STUB))

      stack_versions_mock.reset_mock()
      write_actual_version_to_history_file_mock.reset_mock()
      put_structured_out_mock.reset_mock()

      # Test retrying install again
      stack_versions_mock.side_effect = [
        [OLD_VERSION_STUB, VERSION_STUB],
        [OLD_VERSION_STUB, VERSION_STUB]
      ]
      read_actual_version_from_history_file_mock.return_value = VERSION_STUB

      config_file = self.get_src_folder() + "/test/python/custom_actions/configs/install_packages_config.json"
      with open(config_file, "r") as f:
        command_json = json.load(f)

      command_json['repositoryFile']['repoVersion'] = VERSION_STUB

      lookup_packages.side_effect = TestInstallPackages._add_packages_available
      list_ambari_managed_repos_mock.return_value = []
      self.executeScript("scripts/install_packages.py",
                         classname="InstallPackages",
                         command="actionexecute",
                         config_dict=command_json,
                         target=RMFTestCase.TARGET_CUSTOM_ACTIONS,
                         os_type=('Redhat', '6.4', 'Final'),
                         )
      self.assertTrue(put_structured_out_mock.called)
      self.assertEquals(put_structured_out_mock.call_args[0][0],
                        {'package_installation_result': 'SUCCESS',
                         'repository_version_id': 1,
                         'actual_version': VERSION_STUB})

      self.assertFalse(write_actual_version_to_history_file_mock.called)

  @patch("resource_management.libraries.functions.list_ambari_managed_repos.list_ambari_managed_repos")
  @patch("resource_management.core.providers.get_provider")
  @patch("resource_management.libraries.script.Script.put_structured_out")
  @patch("resource_management.libraries.functions.stack_select.get_stack_versions")
  @patch("resource_management.libraries.functions.repo_version_history.read_actual_version_from_history_file")
  @patch("resource_management.libraries.functions.repo_version_history.write_actual_version_to_history_file")
  @patch("os.path.exists")
  @patch("ambari_commons.shell.subprocess_with_timeout")
  def test_version_reporting__build_number_not_defined_stack_root_present__no_components_installed(self,
                                                                            subprocess_with_timeout,
                                                                            exists_mock,
                                                                            write_actual_version_to_history_file_mock,
                                                                            read_actual_version_from_history_file_mock,
                                                                            stack_versions_mock,
                                                                            put_structured_out_mock, get_provider, list_ambari_managed_repos_mock):
    exists_mock.return_value = True
    stack_versions_mock.side_effect = [
      [],  # before installation attempt
      []
    ]
    read_actual_version_from_history_file_mock.return_value = None

    config_file = self.get_src_folder() + "/test/python/custom_actions/configs/install_packages_config.json"
    with open(config_file, "r") as f:
      command_json = json.load(f)

    command_json['roleParams']['repository_version'] = VERSION_STUB_WITHOUT_BUILD_NUMBER

    from resource_management.core.providers.package.yumrpm import YumProvider
    provider = YumProvider(None)
    with patch.object(provider, "_lookup_packages") as lookup_packages:
      lookup_packages.side_effect = TestInstallPackages._add_packages_available
      get_provider.return_value = provider
      list_ambari_managed_repos_mock.return_value = []

      try:
        self.executeScript("scripts/install_packages.py",
                           classname="InstallPackages",
                           command="actionexecute",
                           config_dict=command_json,
                           target=RMFTestCase.TARGET_CUSTOM_ACTIONS,
                           os_type=('Redhat', '6.4', 'Final'),
                           )
        self.fail("Should throw exception")
      except Fail:
        pass  # Expected

      self.assertTrue(put_structured_out_mock.called)
      self.assertEquals(put_structured_out_mock.call_args_list[-1][0][0],
                        { 'actual_version': '2.2.0.1-885',
                          'package_installation_result': 'FAIL',
                          'repository_version_id': 1})

      self.assertFalse(write_actual_version_to_history_file_mock.called)

      stack_versions_mock.reset_mock()
      write_actual_version_to_history_file_mock.reset_mock()
      put_structured_out_mock.reset_mock()

  @patch("resource_management.libraries.functions.list_ambari_managed_repos.list_ambari_managed_repos")
  @patch("resource_management.core.providers.get_provider")
  @patch("resource_management.libraries.script.Script.put_structured_out")
  @patch("resource_management.libraries.functions.stack_select.get_stack_versions")
  @patch("resource_management.libraries.functions.repo_version_history.read_actual_version_from_history_file")
  @patch("resource_management.libraries.functions.repo_version_history.write_actual_version_to_history_file")
  @patch("os.path.exists")
  @patch("ambari_commons.shell.subprocess_with_timeout")
  def test_version_reporting__build_number_not_defined_stack_root_absent(self,
                                                                        subprocess_with_timeout,
                                                                        exists_mock,
                                                                        write_actual_version_to_history_file_mock,
                                                                        read_actual_version_from_history_file_mock,
                                                                        stack_versions_mock,
                                                                        put_structured_out_mock, get_provider, list_ambari_managed_repos_mock):
    exists_mock.return_value = False
    stack_versions_mock.side_effect = [
      [],  # before installation attempt
      []
    ]
    read_actual_version_from_history_file_mock.return_value = None

    config_file = self.get_src_folder() + "/test/python/custom_actions/configs/install_packages_config.json"
    with open(config_file, "r") as f:
      command_json = json.load(f)

    command_json['repositoryFile']['repoVersion'] = VERSION_STUB_WITHOUT_BUILD_NUMBER

    from resource_management.core.providers.package.yumrpm import YumProvider
    provider = YumProvider(None)
    with patch.object(provider, "_lookup_packages") as lookup_packages:
      lookup_packages.side_effect = TestInstallPackages._add_packages
      get_provider.return_value = provider

      list_ambari_managed_repos_mock.return_value = []
      try:
        self.executeScript("scripts/install_packages.py",
                           classname="InstallPackages",
                           command="actionexecute",
                           config_dict=command_json,
                           target=RMFTestCase.TARGET_CUSTOM_ACTIONS,
                           os_type=('Redhat', '6.4', 'Final'),
                           )
        self.fail("Should throw exception")
      except Fail:
        pass  # Expected

      self.assertTrue(put_structured_out_mock.called)
      self.assertEquals(put_structured_out_mock.call_args_list[-1][0][0],
                        {'package_installation_result': 'FAIL',
                         'repository_version_id': 1})

      self.assertFalse(write_actual_version_to_history_file_mock.called)

      stack_versions_mock.reset_mock()
      write_actual_version_to_history_file_mock.reset_mock()
      put_structured_out_mock.reset_mock()

      # Test retrying install again  (correct build number, provided by other nodes, is now received from server)

      stack_versions_mock.side_effect = [
        [],  # before installation attempt
        []
      ]
      read_actual_version_from_history_file_mock.return_value = None

      config_file = self.get_src_folder() + "/test/python/custom_actions/configs/install_packages_config.json"
      with open(config_file, "r") as f:
        command_json = json.load(f)

      command_json['repositoryFile']['repoVersion'] = VERSION_STUB

      lookup_packages.side_effect = TestInstallPackages._add_packages_available
      list_ambari_managed_repos_mock.return_value = []
      try:
        self.executeScript("scripts/install_packages.py",
                         classname="InstallPackages",
                         command="actionexecute",
                         config_dict=command_json,
                         target=RMFTestCase.TARGET_CUSTOM_ACTIONS,
                         os_type=('Redhat', '6.4', 'Final'),
                         )
        self.fail("Should throw exception")
      except Fail:
        pass  # Expected

      self.assertTrue(put_structured_out_mock.called)
      self.assertEquals(put_structured_out_mock.call_args[0][0],
                        {'package_installation_result': 'FAIL',
                         'repository_version_id': 1,
                         'actual_version': VERSION_STUB})

      self.assertFalse(write_actual_version_to_history_file_mock.called)

  @patch("resource_management.libraries.functions.list_ambari_managed_repos.list_ambari_managed_repos")
  @patch("resource_management.core.providers.get_provider")
  @patch("resource_management.libraries.script.Script.put_structured_out")
  @patch("resource_management.libraries.functions.stack_select.get_stack_versions")
  @patch("resource_management.libraries.functions.repo_version_history.read_actual_version_from_history_file")
  @patch("resource_management.libraries.functions.repo_version_history.write_actual_version_to_history_file")
  @patch("ambari_commons.shell.subprocess_with_timeout")
  def test_version_reporting__build_number_not_defined_stack_root_present(self,
                                                                    subprocess_with_timeout,
                                                                    write_actual_version_to_history_file_mock,
                                                                    read_actual_version_from_history_file_mock,
                                                                    stack_versions_mock,
                                                                    put_structured_out_mock, get_provider, list_ambari_managed_repos_mock):
    stack_versions_mock.side_effect = [
      [OLD_VERSION_STUB],  # before installation attempt
      [OLD_VERSION_STUB, VERSION_STUB]
    ]

    config_file = self.get_src_folder() + "/test/python/custom_actions/configs/install_packages_config.json"
    with open(config_file, "r") as f:
      command_json = json.load(f)

    command_json['roleParams']['repository_version'] = VERSION_STUB_WITHOUT_BUILD_NUMBER

    from resource_management.core.providers.package.yumrpm import YumProvider
    provider = YumProvider(None)
    with patch.object(provider, "_lookup_packages") as lookup_packages:
      lookup_packages.side_effect = TestInstallPackages._add_packages_available
      get_provider.return_value = provider
      list_ambari_managed_repos_mock.return_value = []
      self.executeScript("scripts/install_packages.py",
                         classname="InstallPackages",
                         command="actionexecute",
                         config_dict=command_json,
                         target=RMFTestCase.TARGET_CUSTOM_ACTIONS,
                         os_type=('Redhat', '6.4', 'Final'),
                         )
      self.assertTrue(put_structured_out_mock.called)
      self.assertEquals(put_structured_out_mock.call_args[0][0],
                        {'package_installation_result': 'SUCCESS',
                         'repository_version_id': 1,
                         'actual_version': VERSION_STUB})
      self.assertTrue(write_actual_version_to_history_file_mock.called)
      self.assertEquals(write_actual_version_to_history_file_mock.call_args[0], (VERSION_STUB_WITHOUT_BUILD_NUMBER, VERSION_STUB))

      stack_versions_mock.reset_mock()
      write_actual_version_to_history_file_mock.reset_mock()
      put_structured_out_mock.reset_mock()

      # Test retrying install again
      stack_versions_mock.side_effect = [
        [OLD_VERSION_STUB, VERSION_STUB],
        [OLD_VERSION_STUB, VERSION_STUB]
      ]
      read_actual_version_from_history_file_mock.return_value = VERSION_STUB

      config_file = self.get_src_folder() + "/test/python/custom_actions/configs/install_packages_config.json"
      with open(config_file, "r") as f:
        command_json = json.load(f)

      command_json['repositoryFile']['repoVersion'] = VERSION_STUB_WITHOUT_BUILD_NUMBER

      lookup_packages.side_effect = TestInstallPackages._add_packages_available
      list_ambari_managed_repos_mock.return_value = []
      self.executeScript("scripts/install_packages.py",
                         classname="InstallPackages",
                         command="actionexecute",
                         config_dict=command_json,
                         target=RMFTestCase.TARGET_CUSTOM_ACTIONS,
                         os_type=('Redhat', '6.4', 'Final'),
                         )
      self.assertTrue(put_structured_out_mock.called)
      self.assertEquals(put_structured_out_mock.call_args[0][0],
                        {'package_installation_result': 'SUCCESS',
                         'repository_version_id': 1,
                         'actual_version': VERSION_STUB})

      self.assertFalse(write_actual_version_to_history_file_mock.called)

  @patch("resource_management.libraries.functions.list_ambari_managed_repos.list_ambari_managed_repos")
  @patch("resource_management.core.providers.get_provider")
  @patch("resource_management.libraries.script.Script.put_structured_out")
  @patch("resource_management.libraries.functions.stack_select.get_stack_versions")
  @patch("resource_management.libraries.functions.repo_version_history.read_actual_version_from_history_file")
  @patch("resource_management.libraries.functions.repo_version_history.write_actual_version_to_history_file")
  @patch("ambari_commons.shell.subprocess_with_timeout")
  def test_version_reporting__wrong_build_number_specified_stack_root_present(self,
                                                                        subprocess_with_timeout,
                                                                        write_actual_version_to_history_file_mock,
                                                                        read_actual_version_from_history_file_mock,
                                                                        stack_versions_mock,
                                                                        put_structured_out_mock, get_provider, list_ambari_managed_repos_mock):
    stack_versions_mock.side_effect = [
      [OLD_VERSION_STUB],  # before installation attempt
      [OLD_VERSION_STUB, VERSION_STUB]
    ]

    config_file = self.get_src_folder() + "/test/python/custom_actions/configs/install_packages_config.json"
    with open(config_file, "r") as f:
      command_json = json.load(f)

    command_json['repositoryFile']['repoVersion'] = '2.2.0.1-500'  # User specified wrong build number

    from resource_management.core.providers.package.yumrpm import YumProvider
    provider = YumProvider(None)
    with patch.object(provider, "_lookup_packages") as lookup_packages:
      lookup_packages.side_effect = TestInstallPackages._add_packages_available
      get_provider.return_value = provider
      list_ambari_managed_repos_mock.return_value = []
      self.executeScript("scripts/install_packages.py",
                         classname="InstallPackages",
                         command="actionexecute",
                         config_dict=command_json,
                         target=RMFTestCase.TARGET_CUSTOM_ACTIONS,
                         os_type=('Redhat', '6.4', 'Final'),
                         )
      self.assertTrue(put_structured_out_mock.called)
      self.assertEquals(put_structured_out_mock.call_args[0][0],
                        {'package_installation_result': 'SUCCESS',
                         'repository_version_id': 1,
                         'actual_version': VERSION_STUB})
      self.assertTrue(write_actual_version_to_history_file_mock.called)
      self.assertEquals(write_actual_version_to_history_file_mock.call_args[0], ('2.2.0.1', VERSION_STUB))

      stack_versions_mock.reset_mock()
      write_actual_version_to_history_file_mock.reset_mock()
      put_structured_out_mock.reset_mock()

      # Test retrying install again
      stack_versions_mock.side_effect = [
        [OLD_VERSION_STUB, VERSION_STUB],
        [OLD_VERSION_STUB, VERSION_STUB]
      ]
      read_actual_version_from_history_file_mock.return_value = VERSION_STUB

      config_file = self.get_src_folder() + "/test/python/custom_actions/configs/install_packages_config.json"
      with open(config_file, "r") as f:
        command_json = json.load(f)

      command_json['roleParams']['repository_version'] = '2.2.0.1-500'  # User specified wrong build number

      lookup_packages.side_effect = TestInstallPackages._add_packages_available
      list_ambari_managed_repos_mock.return_value = []
      self.executeScript("scripts/install_packages.py",
                         classname="InstallPackages",
                         command="actionexecute",
                         config_dict=command_json,
                         target=RMFTestCase.TARGET_CUSTOM_ACTIONS,
                         os_type=('Redhat', '6.4', 'Final'),
                         )
      self.assertTrue(put_structured_out_mock.called)
      self.assertEquals(put_structured_out_mock.call_args[0][0],
                        {'package_installation_result': 'SUCCESS',
                         'repository_version_id': 1,
                         'actual_version': VERSION_STUB})

      self.assertFalse(write_actual_version_to_history_file_mock.called)

  @patch("resource_management.libraries.functions.list_ambari_managed_repos.list_ambari_managed_repos")
  @patch("resource_management.core.providers.get_provider")
  @patch("resource_management.libraries.script.Script.put_structured_out")
  @patch("resource_management.libraries.functions.stack_select.get_stack_versions")
  @patch("resource_management.libraries.functions.repo_version_history.read_actual_version_from_history_file")
  @patch("resource_management.libraries.functions.repo_version_history.write_actual_version_to_history_file")
  @patch("os.path.exists")
  @patch("ambari_commons.shell.subprocess_with_timeout")
  def test_version_reporting__wrong_build_number_specified_stack_root_absent(self,
                                                                            subprocess_with_timeout,
                                                                            exists_mock,
                                                                            write_actual_version_to_history_file_mock,
                                                                            read_actual_version_from_history_file_mock,
                                                                            stack_versions_mock,
                                                                            put_structured_out_mock, get_provider, list_ambari_managed_repos_mock):
    exists_mock.return_value = False
    stack_versions_mock.side_effect = [
      [],  # before installation attempt
      []
    ]
    read_actual_version_from_history_file_mock.return_value = None

    config_file = self.get_src_folder() + "/test/python/custom_actions/configs/install_packages_config.json"
    with open(config_file, "r") as f:
      command_json = json.load(f)

    command_json['repositoryFile']['repoVersion'] = VERSION_STUB_WITHOUT_BUILD_NUMBER

    from resource_management.core.providers.package.yumrpm import YumProvider
    provider = YumProvider(None)
    with patch.object(provider, "_lookup_packages") as lookup_packages:
      lookup_packages.side_effect = TestInstallPackages._add_packages_available
      get_provider.return_value = provider
      list_ambari_managed_repos_mock.return_value = []
      try:
        self.executeScript("scripts/install_packages.py",
                           classname="InstallPackages",
                           command="actionexecute",
                           config_dict=command_json,
                           target=RMFTestCase.TARGET_CUSTOM_ACTIONS,
                           os_type=('Redhat', '6.4', 'Final'),
                           )
        self.fail("Should throw exception")
      except Fail:
        pass  # Expected

      self.assertTrue(put_structured_out_mock.called)
      self.assertEquals(put_structured_out_mock.call_args_list[-1][0][0],
                        {'package_installation_result': 'FAIL',
                         'repository_version_id': 1})

      self.assertFalse(write_actual_version_to_history_file_mock.called)

      stack_versions_mock.reset_mock()
      write_actual_version_to_history_file_mock.reset_mock()
      put_structured_out_mock.reset_mock()

      # Test retrying install again (correct build number, provided by other nodes, is now received from server)

      stack_versions_mock.side_effect = [
        [],  # before installation attempt
        []
      ]
      read_actual_version_from_history_file_mock.return_value = None

      config_file = self.get_src_folder() + "/test/python/custom_actions/configs/install_packages_config.json"
      with open(config_file, "r") as f:
        command_json = json.load(f)

      command_json['roleParams']['repository_version'] = VERSION_STUB

      lookup_packages.side_effect = TestInstallPackages._add_packages_available
      list_ambari_managed_repos_mock.return_value = []
      try:
        self.executeScript("scripts/install_packages.py",
                         classname="InstallPackages",
                         command="actionexecute",
                         config_dict=command_json,
                         target=RMFTestCase.TARGET_CUSTOM_ACTIONS,
                         os_type=('Redhat', '6.4', 'Final'),
                         )
        self.fail("Should throw exception")
      except Fail:
        pass  # Expected

      self.assertTrue(put_structured_out_mock.called)
      self.assertEquals(put_structured_out_mock.call_args[0][0],
                        {'package_installation_result': 'FAIL',
                         'repository_version_id': 1,
                         'actual_version': VERSION_STUB})

      self.assertFalse(write_actual_version_to_history_file_mock.called)

  @patch("resource_management.libraries.functions.list_ambari_managed_repos.list_ambari_managed_repos")
  @patch("resource_management.core.providers.get_provider")
  @patch("resource_management.libraries.script.Script.put_structured_out")
  @patch("resource_management.libraries.functions.stack_select.get_stack_versions")
  @patch("resource_management.libraries.functions.repo_version_history.read_actual_version_from_history_file")
  @patch("resource_management.libraries.functions.repo_version_history.write_actual_version_to_history_file")
  @patch("ambari_commons.shell.subprocess_with_timeout")
  def test_version_reporting_with_repository_version(self,
                                                     subprocess_with_timeout,
                                                     write_actual_version_to_history_file_mock,
                                                     read_actual_version_from_history_file_mock,
                                                     stack_versions_mock,
                                                     put_structured_out_mock, get_provider, list_ambari_managed_repos_mock):
    stack_versions_mock.side_effect = [
      [OLD_VERSION_STUB],  # before installation attempt
      [OLD_VERSION_STUB, VERSION_STUB]
    ]

    config_file = self.get_src_folder() + "/test/python/custom_actions/configs/install_packages_config.json"
    with open(config_file, "r") as f:
      command_json = json.load(f)

    command_json['roleParams']['repository_version'] = VERSION_STUB
    command_json['roleParams']['repository_version_id'] = '2'

    from resource_management.core.providers.package.yumrpm import YumProvider
    provider = YumProvider(None)
    with patch.object(provider, "_lookup_packages") as lookup_packages:
      lookup_packages.side_effect = TestInstallPackages._add_packages_available
      get_provider.return_value = provider
      list_ambari_managed_repos_mock.return_value = []
      self.executeScript("scripts/install_packages.py",
                         classname="InstallPackages",
                         command="actionexecute",
                         config_dict=command_json,
                         target=RMFTestCase.TARGET_CUSTOM_ACTIONS,
                         os_type=('Redhat', '6.4', 'Final'),
                         )
      self.assertTrue(put_structured_out_mock.called)
      self.assertEquals(put_structured_out_mock.call_args[0][0],
                        {'package_installation_result': 'SUCCESS',
                         'repository_version_id': 1,
                         'actual_version': VERSION_STUB})
      self.assertTrue(write_actual_version_to_history_file_mock.called)
      self.assertEquals(write_actual_version_to_history_file_mock.call_args[0], (VERSION_STUB_WITHOUT_BUILD_NUMBER, VERSION_STUB))

      stack_versions_mock.reset_mock()
      write_actual_version_to_history_file_mock.reset_mock()
      put_structured_out_mock.reset_mock()

      # Test retrying install again
      stack_versions_mock.side_effect = [
        [OLD_VERSION_STUB, VERSION_STUB],
        [OLD_VERSION_STUB, VERSION_STUB]
      ]
      read_actual_version_from_history_file_mock.return_value = VERSION_STUB

      config_file = self.get_src_folder() + "/test/python/custom_actions/configs/install_packages_config.json"
      with open(config_file, "r") as f:
        command_json = json.load(f)

      command_json['roleParams']['repository_version'] = VERSION_STUB
      command_json['roleParams']['repository_version_id'] = '2'

      lookup_packages.side_effect = TestInstallPackages._add_packages_available
      list_ambari_managed_repos_mock.return_value = []
      self.executeScript("scripts/install_packages.py",
                         classname="InstallPackages",
                         command="actionexecute",
                         config_dict=command_json,
                         target=RMFTestCase.TARGET_CUSTOM_ACTIONS,
                         os_type=('Redhat', '6.4', 'Final'),
                         )
      self.assertTrue(put_structured_out_mock.called)
      self.assertEquals(put_structured_out_mock.call_args[0][0],
                        {'package_installation_result': 'SUCCESS',
                         'repository_version_id': 1,
                         'actual_version': VERSION_STUB})

      self.assertFalse(write_actual_version_to_history_file_mock.called)

  @patch("resource_management.libraries.functions.list_ambari_managed_repos.list_ambari_managed_repos")
  @patch("resource_management.core.providers.get_provider")
  @patch("resource_management.libraries.script.Script.put_structured_out")
  @patch("resource_management.libraries.functions.stack_select.get_stack_versions")
  @patch("resource_management.libraries.functions.repo_version_history.read_actual_version_from_history_file")
  @patch("resource_management.libraries.functions.repo_version_history.write_actual_version_to_history_file")
  @patch("ambari_commons.shell.subprocess_with_timeout")
  def test_normal_flow_rhel_with_command_repo(self,
                                              subprocess_with_timeout,
                                              write_actual_version_to_history_file_mock,
                                              read_actual_version_from_history_file_mock,
                                              stack_versions_mock,
                                              put_structured_out_mock,
                                              get_provider,
                                              list_ambari_managed_repos_mock):
    stack_versions_mock.side_effect = [
      [],  # before installation attempt
      [VERSION_STUB]
    ]
    from resource_management.core.providers.package.yumrpm import YumProvider
    provider = YumProvider(None)
    with patch.object(provider, "_lookup_packages") as lookup_packages:
      lookup_packages.side_effect = TestInstallPackages._add_packages_lookUpYum
      get_provider.return_value = provider
      list_ambari_managed_repos_mock.return_value=[]
      repo_file_name = 'ambari-hdp-4'
      use_repos = { 'HDP-UTILS-1.1.0.20-repo-4': repo_file_name, 'HDP-2.2-repo-4': repo_file_name }
      self.executeScript("scripts/install_packages.py",
                         classname="InstallPackages",
                         command="actionexecute",
                         config_file="install_packages_repository_file.json",
                         target=RMFTestCase.TARGET_CUSTOM_ACTIONS,
                         os_type=('Redhat', '6.4', 'Final'),
      )
      self.assertTrue(put_structured_out_mock.called)
      self.assertEquals(put_structured_out_mock.call_args[0][0],
                        {'package_installation_result': 'SUCCESS',
                         'repository_version_id': 4,
                         'actual_version': VERSION_STUB})

      self.assertResourceCalled('Repository', 'HDP-UTILS-1.1.0.20-repo-4',
                                base_url=u'http://repo1/HDP-UTILS/centos5/2.x/updates/2.2.0.0',
                                action=['create'],
                                components=[u'HDP-UTILS', 'main'],
                                repo_template='[{{repo_id}}]\nname={{repo_id}}\n{% if mirror_list %}mirrorlist={{mirror_list}}{% else %}baseurl={{base_url}}{% endif %}\n\npath=/\nenabled=1\ngpgcheck=0',
                                repo_file_name=repo_file_name,
                                mirror_list=None,
                                append_to_file=False,
      )
      self.assertResourceCalled('Repository', 'HDP-2.2-repo-4',
                                base_url=u'http://repo1/HDP/centos5/2.x/updates/2.2.0.0',
                                action=['create'],
                                components=[u'HDP', 'main'],
                                repo_template='[{{repo_id}}]\nname={{repo_id}}\n{% if mirror_list %}mirrorlist={{mirror_list}}{% else %}baseurl={{base_url}}{% endif %}\n\npath=/\nenabled=1\ngpgcheck=0',
                                repo_file_name=repo_file_name,
                                mirror_list=None,
                                append_to_file=True,
      )
      self.assertResourceCalled('Package', 'hdp-select', action=["upgrade"], use_repos=use_repos, retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'hadoop_2_2_0_1_885', action=["upgrade"], retry_count=5,
                                retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'snappy', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'snappy-devel', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'lzo', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'hadooplzo_2_2_0_1_885', action=["upgrade"], retry_count=5,
                                retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'hadoop_2_2_0_1_885-libhdfs', action=["upgrade"], retry_count=5,
                                retry_on_repo_unavailability=False)
      self.assertResourceCalled('Package', 'ambari-log4j', action=["upgrade"], retry_count=5, retry_on_repo_unavailability=False)
      self.assertNoMoreResources()


text:
var principal = Titanium.UI.currentWindow;

principal.backgroundColor = '#000';

var imagen = Titanium.UI.createImageView({
	image:'../logoUACM.jpg',
	width:'150dp',
	height:'150dp',
	top:'20dp'
});

imagen.addEventListener('click', function(e){
	var mapa = Titanium.UI.createWindow({
		url:'ui/mapa.js'
	});
	mapa.open({modal:true});
})

principal.add(imagen);

var web = Titanium.UI.createWebView({
	url:'http://www.google.com',
	top:'200dp'
});

principal.add(web);


text:
<html><head><meta charset='utf-8'>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<style type="text/css">
body {padding:0; margin:0;}
.C { position:absolute; -webkit-user-select: none;}
</style>
</head>
<body>

<canvas id='b' width=800 height=600 class="C"></canvas>
<canvas id='c' width=800 height=600 class="C"></canvas>
<canvas id='d' width=800 height=600 class="C"></canvas>

<script type="text/javascript" src="consts.js"></script>
<script type="text/javascript" src="jsfxr.js"></script>
<script type="text/javascript" src="coins.js"></script>
<script type="text/javascript" src="game.js"></script>
<script type="text/javascript" src="enemy.js"></script>
<!--<script type="text/javascript" src="test_lvl.js"></script>-->
<script type="text/javascript" src="lvl1.js"></script>
<script type="text/javascript" src="lvl2.js"></script>
<script type="text/javascript" src="intro.js"></script>
<script type="text/javascript" src="player.js"></script>
<script type="text/javascript" src="loop.js"></script>

<!--<script type="text/javascript" src="../js13.js"></script>-->
</body></html>


text:
ActiveRecord::Schema.define(version: 20160825015916) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "activities", force: :cascade do |t|
    t.string   "name"
    t.string   "instructor"
    t.date     "start"
    t.date     "end"
    t.string   "times"
    t.integer  "max_seats",                                default: 100, null: false
    t.boolean  "visible"
    t.datetime "created_at",                                             null: false
    t.datetime "updated_at",                                             null: false
    t.text     "description"
    t.decimal  "cost",             precision: 6, scale: 2, default: 0.0, null: false
    t.integer  "min_seats",                                default: 1,   null: false
    t.boolean  "cash_only"
    t.integer  "min_grade",                                default: 0,   null: false
    t.integer  "max_grade",                                default: 5,   null: false
    t.string   "category"
    t.text     "html_description"
    t.string   "vendor_email"
    t.string   "vendor_phone"
    t.integer  "season_id"
  end

  add_index "activities", ["season_id"], name: "index_activities_on_season_id", using: :btree

  create_table "enrollments", force: :cascade do |t|
    t.integer  "activity_id"
    t.integer  "student_id"
    t.boolean  "low_income"
    t.boolean  "committed"
    t.datetime "created_at",                    null: false
    t.datetime "updated_at",                    null: false
    t.string   "payment_type", default: "none"
  end

  add_index "enrollments", ["activity_id"], name: "index_enrollments_on_activity_id", using: :btree
  add_index "enrollments", ["student_id"], name: "index_enrollments_on_student_id", using: :btree

  create_table "parents", force: :cascade do |t|
    t.string   "first_name"
    t.string   "last_name"
    t.string   "email"
    t.string   "phone_number"
    t.string   "role"
    t.datetime "created_at",                          null: false
    t.datetime "updated_at",                          null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.inet     "current_sign_in_ip"
    t.inet     "last_sign_in_ip"
  end

  add_index "parents", ["email"], name: "index_parents_on_email", unique: true, using: :btree
  add_index "parents", ["reset_password_token"], name: "index_parents_on_reset_password_token", unique: true, using: :btree

  create_table "seasons", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "students", force: :cascade do |t|
    t.string   "first_name"
    t.string   "last_name"
    t.integer  "parent_id"
    t.integer  "grade"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer  "teacher_id"
    t.string   "full_name"
    t.string   "uuid"
  end

  add_index "students", ["full_name"], name: "index_students_on_full_name", using: :btree
  add_index "students", ["last_name"], name: "index_students_on_last_name", using: :btree
  add_index "students", ["parent_id"], name: "index_students_on_parent_id", using: :btree
  add_index "students", ["teacher_id"], name: "index_students_on_teacher_id", using: :btree
  add_index "students", ["uuid"], name: "index_students_on_uuid", unique: true, using: :btree

  create_table "teachers", force: :cascade do |t|
    t.string   "title"
    t.string   "first_name"
    t.string   "last_name"
    t.string   "room"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  add_index "teachers", ["last_name", "first_name"], name: "index_teachers_on_last_name_and_first_name", unique: true, using: :btree

  create_table "walkathon_lap_counts", force: :cascade do |t|
    t.integer  "student_id"
    t.integer  "lap_count"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "walkathon_lap_counts", ["student_id"], name: "index_walkathon_lap_counts_on_student_id", unique: true, using: :btree

  create_table "walkathon_payments", force: :cascade do |t|
    t.string   "description"
    t.decimal  "amount",              precision: 7, scale: 2
    t.integer  "walkathon_pledge_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "walkathon_payments", ["walkathon_pledge_id"], name: "index_walkathon_payments_on_walkathon_pledge_id", using: :btree

  create_table "walkathon_pledges", force: :cascade do |t|
    t.string   "sponsor_name"
    t.string   "sponsor_phone"
    t.string   "sponsor_email"
    t.integer  "lap_count"
    t.string   "pledge_type"
    t.decimal  "pledge_per_lap",   precision: 5, scale: 2
    t.decimal  "maximum_pledge",   precision: 7, scale: 2
    t.decimal  "fixed_pledge",     precision: 7, scale: 2
    t.decimal  "committed_amount", precision: 7, scale: 2
    t.decimal  "paid_amount",      precision: 7, scale: 2
    t.integer  "student_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "walkathon_pledges", ["student_id"], name: "index_walkathon_pledges_on_student_id", using: :btree

  add_foreign_key "activities", "seasons"
  add_foreign_key "enrollments", "activities"
  add_foreign_key "enrollments", "students"
  add_foreign_key "students", "parents"
  add_foreign_key "students", "teachers"
  add_foreign_key "walkathon_lap_counts", "students"
  add_foreign_key "walkathon_payments", "walkathon_pledges"
  add_foreign_key "walkathon_pledges", "students"
end


text:
module Albacore
  module Configuration
    def self.included(base)
      Albacore.configuration.extend(base) if (base.class == Module)
    end
  end

  class ConfigData
   	attr_accessor :yaml_config_folder, :log_level
  end

  class << self
    def configure
      yield(configuration) if block_given?
      configuration
    end

    def configuration
      @configuration ||= ConfigData.new
    end
  end
end