<commit_before>#* This file is part of the MOOSE framework
#* https://www.mooseframework.org
#*
#* All rights reserved, see COPYRIGHT for full restrictions
#* https://github.com/idaholab/moose/blob/master/COPYRIGHT
#*
#* Licensed under LGPL 2.1, please see LICENSE for details
#* https://www.gnu.org/licenses/lgpl-2.1.html

"""
python TestPostprocessorPluginManager_test_script.py
"""
import matplotlib.pyplot as plt
import mooseutils

# Create Figure and Axes
figure = plt.figure(facecolor='white')
axes0 = figure.add_subplot(111)
axes1 = axes0.twinx()

# Read Postprocessor Data
data = mooseutils.PostprocessorReader('../input/white_elephant_jan_2016.csv')
x = data('time')

y = data('air_temp_set_1')
axes1.plot(x, y, marker='', linewidth=5.0, color=[0.2, 0.627, 0.173, 1.0], markersize=1, linestyle=u'--', label='air_temp_set_1')

# Axes Settings
axes1.legend(loc='lower right')
axes0.set_title('Snow Data')

# y1-axis Settings
axes1.set_ylabel('Air Temperature [C]')
axes1.set_ylim([0.0, 35.939999999999998])

# Show figure and write pdf
plt.show()
figure.savefig("output.pdf")
<commit_msg>Remove header added to gold file<commit_after>"""
python TestPostprocessorPluginManager_test_script.py
"""
import matplotlib.pyplot as plt
import mooseutils

# Create Figure and Axes
figure = plt.figure(facecolor='white')
axes0 = figure.add_subplot(111)
axes1 = axes0.twinx()

# Read Postprocessor Data
data = mooseutils.PostprocessorReader('../input/white_elephant_jan_2016.csv')
x = data('time')

y = data('air_temp_set_1')
axes1.plot(x, y, marker='', linewidth=5.0, color=[0.2, 0.627, 0.173, 1.0], markersize=1, linestyle=u'--', label='air_temp_set_1')

# Axes Settings
axes1.legend(loc='lower right')
axes0.set_title('Snow Data')

# y1-axis Settings
axes1.set_ylabel('Air Temperature [C]')
axes1.set_ylim([0.0, 35.939999999999998])

# Show figure and write pdf
plt.show()
figure.savefig("output.pdf")
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

import datetime
from dateutil.relativedelta import relativedelta
import logging
from operator import itemgetter
from os.path import join as opj
import time

from openerp import netsvc, tools
from openerp.tools.translate import _
from openerp.osv import fields, osv

_logger = logging.getLogger(__name__)

class account_installer(osv.osv_memory):
    _name = 'account.installer'
    _inherit = 'res.config.installer'

    def _get_charts(self, cr, uid, context=None):
        modules = self.pool.get('ir.module.module')
        # Looking for the module with the 'Account Charts' category
        category_name, category_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'base', 'module_category_localization_account_charts')
        ids = modules.search(cr, uid, [('category_id', '=', category_id)], context=context)
        charts = list(
            sorted(((m.name, m.shortdesc)
                    for m in modules.browse(cr, uid, ids, context=context)),
                   key=itemgetter(1)))
        charts.insert(0, ('configurable', _('Custom')))
        return charts

    _columns = {
        # Accounting
        'charts': fields.selection(_get_charts, 'Accounting Package',
            required=True,
            help="Installs localized accounting charts to match as closely as "
                 "possible the accounting needs of your company based on your "
                 "country."),
        'date_start': fields.date('Start Date', required=True),
        'date_stop': fields.date('End Date', required=True),
        'period': fields.selection([('month', 'Monthly'), ('3months','3 Monthly')], 'Periods', required=True),
        'company_id': fields.many2one('res.company', 'Company', required=True),
        'has_default_company' : fields.boolean('Has Default Company', readonly=True),
    }

    def _default_company(self, cr, uid, context=None):
        user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
        return user.company_id and user.company_id.id or False

    def _default_has_default_company(self, cr, uid, context=None):
        count = self.pool.get('res.company').search_count(cr, uid, [], context=context)
        return bool(count == 1)

    _defaults = {
        'date_start': lambda *a: time.strftime('%Y-01-01'),
        'date_stop': lambda *a: time.strftime('%Y-12-31'),
        'period': 'month',
        'company_id': _default_company,
        'has_default_company': _default_has_default_company,
        'charts': 'configurable'
    }

    def get_unconfigured_cmp(self, cr, uid, context=None):
        """ get the list of companies that have not been configured yet
        but don't care about the demo chart of accounts """
        cmp_select = []
        company_ids = self.pool.get('res.company').search(cr, uid, [], context=context)
        cr.execute("SELECT company_id FROM account_account WHERE active = 't' AND account_account.parent_id IS NULL AND name != %s", ("Chart For Automated Tests",))
        configured_cmp = [r[0] for r in cr.fetchall()]
        return list(set(company_ids)-set(configured_cmp))

    def check_unconfigured_cmp(self, cr, uid, context=None):
        """ check if there are still unconfigured companies """
        if not self.get_unconfigured_cmp(cr, uid, context=context):
            raise osv.except_osv(_('No unconfigured company !'), _("There is currently no company without chart of account. The wizard will therefore not be executed."))

    def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
        if context is None:context = {}
        res = super(account_installer, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar,submenu=False)
        cmp_select = []
        # display in the widget selection only the companies that haven't been configured yet
        unconfigured_cmp = self.get_unconfigured_cmp(cr, uid, context=context)
        for field in res['fields']:
            if field == 'company_id':
                res['fields'][field]['domain'] = [('id','in',unconfigured_cmp)]
                res['fields'][field]['selection'] = [('', '')]
                if unconfigured_cmp:
                    cmp_select = [(line.id, line.name) for line in self.pool.get('res.company').browse(cr, uid, unconfigured_cmp)]
                    res['fields'][field]['selection'] = cmp_select
        return res

    def on_change_start_date(self, cr, uid, id, start_date=False):
        if start_date:
            start_date = datetime.datetime.strptime(start_date, "%Y-%m-%d")
            end_date = (start_date + relativedelta(months=12)) - relativedelta(days=1)
            return {'value': {'date_stop': end_date.strftime('%Y-%m-%d')}}
        return {}

    def execute(self, cr, uid, ids, context=None):
        self.execute_simple(cr, uid, ids, context)
        super(account_installer, self).execute(cr, uid, ids, context=context)

    def execute_simple(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        fy_obj = self.pool.get('account.fiscalyear')
        for res in self.read(cr, uid, ids, context=context):
            if 'date_start' in res and 'date_stop' in res:
                f_ids = fy_obj.search(cr, uid, [('date_start', '<=', res['date_start']), ('date_stop', '>=', res['date_stop']), ('company_id', '=', res['company_id'][0])], context=context)
                if not f_ids:
                    name = code = res['date_start'][:4]
                    if int(name) != int(res['date_stop'][:4]):
                        name = res['date_start'][:4] +'-'+ res['date_stop'][:4]
                        code = res['date_start'][2:4] +'-'+ res['date_stop'][2:4]
                    vals = {
                        'name': name,
                        'code': code,
                        'date_start': res['date_start'],
                        'date_stop': res['date_stop'],
                        'company_id': res['company_id'][0]
                    }
                    fiscal_id = fy_obj.create(cr, uid, vals, context=context)
                    if res['period'] == 'month':
                        fy_obj.create_period(cr, uid, [fiscal_id])
                    elif res['period'] == '3months':
                        fy_obj.create_period3(cr, uid, [fiscal_id])

    def modules_to_install(self, cr, uid, ids, context=None):
        modules = super(account_installer, self).modules_to_install(
            cr, uid, ids, context=context)
        chart = self.read(cr, uid, ids, ['charts'],
                          context=context)[0]['charts']
        _logger.debug('Installing chart of accounts %s', chart)
        return modules | set([chart])

account_installer()

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
<commit_msg>[IMP] account: installer get list of charts from apps<commit_after># -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

import datetime
from dateutil.relativedelta import relativedelta
import logging
from operator import itemgetter
import time
import urllib2
import urlparse

try:
    import simplejson as json
except ImportError:
    import json     # noqa

from openerp.release import serie
from openerp.tools.translate import _
from openerp.osv import fields, osv

_logger = logging.getLogger(__name__)

class account_installer(osv.osv_memory):
    _name = 'account.installer'
    _inherit = 'res.config.installer'

    def _get_charts(self, cr, uid, context=None):
        modules = self.pool.get('ir.module.module')

        # try get the list on apps server
        try:
            apps_server = self.pool.get('ir.config_parameter').get_value(cr, uid, 'apps.server', 'https://apps.openerp.com')

            up = urlparse.urlparse(apps_server)
            url = '{0.scheme}://{0.netloc}/apps/charts?serie={1}'.format(up, serie)

            j = urllib2.urlopen(url, timeout=3).read()
            apps_charts = json.loads(j)

            charts = dict(apps_charts)
        except Exception:
            charts = dict()

        # Looking for the module with the 'Account Charts' category
        category_name, category_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'base', 'module_category_localization_account_charts')
        ids = modules.search(cr, uid, [('category_id', '=', category_id)], context=context)
        if ids:
            charts.update((m.name, m.shortdesc) for m in modules.browse(cr, uid, ids, context=context))

        charts = sorted(charts.items(), key=itemgetter(1))
        charts.insert(0, ('configurable', _('Custom')))
        return charts

    _columns = {
        # Accounting
        'charts': fields.selection(_get_charts, 'Accounting Package',
            required=True,
            help="Installs localized accounting charts to match as closely as "
                 "possible the accounting needs of your company based on your "
                 "country."),
        'date_start': fields.date('Start Date', required=True),
        'date_stop': fields.date('End Date', required=True),
        'period': fields.selection([('month', 'Monthly'), ('3months','3 Monthly')], 'Periods', required=True),
        'company_id': fields.many2one('res.company', 'Company', required=True),
        'has_default_company' : fields.boolean('Has Default Company', readonly=True),
    }

    def _default_company(self, cr, uid, context=None):
        user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
        return user.company_id and user.company_id.id or False

    def _default_has_default_company(self, cr, uid, context=None):
        count = self.pool.get('res.company').search_count(cr, uid, [], context=context)
        return bool(count == 1)

    _defaults = {
        'date_start': lambda *a: time.strftime('%Y-01-01'),
        'date_stop': lambda *a: time.strftime('%Y-12-31'),
        'period': 'month',
        'company_id': _default_company,
        'has_default_company': _default_has_default_company,
        'charts': 'configurable'
    }

    def get_unconfigured_cmp(self, cr, uid, context=None):
        """ get the list of companies that have not been configured yet
        but don't care about the demo chart of accounts """
        cmp_select = []
        company_ids = self.pool.get('res.company').search(cr, uid, [], context=context)
        cr.execute("SELECT company_id FROM account_account WHERE active = 't' AND account_account.parent_id IS NULL AND name != %s", ("Chart For Automated Tests",))
        configured_cmp = [r[0] for r in cr.fetchall()]
        return list(set(company_ids)-set(configured_cmp))

    def check_unconfigured_cmp(self, cr, uid, context=None):
        """ check if there are still unconfigured companies """
        if not self.get_unconfigured_cmp(cr, uid, context=context):
            raise osv.except_osv(_('No unconfigured company !'), _("There is currently no company without chart of account. The wizard will therefore not be executed."))

    def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
        if context is None:context = {}
        res = super(account_installer, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar,submenu=False)
        cmp_select = []
        # display in the widget selection only the companies that haven't been configured yet
        unconfigured_cmp = self.get_unconfigured_cmp(cr, uid, context=context)
        for field in res['fields']:
            if field == 'company_id':
                res['fields'][field]['domain'] = [('id','in',unconfigured_cmp)]
                res['fields'][field]['selection'] = [('', '')]
                if unconfigured_cmp:
                    cmp_select = [(line.id, line.name) for line in self.pool.get('res.company').browse(cr, uid, unconfigured_cmp)]
                    res['fields'][field]['selection'] = cmp_select
        return res

    def on_change_start_date(self, cr, uid, id, start_date=False):
        if start_date:
            start_date = datetime.datetime.strptime(start_date, "%Y-%m-%d")
            end_date = (start_date + relativedelta(months=12)) - relativedelta(days=1)
            return {'value': {'date_stop': end_date.strftime('%Y-%m-%d')}}
        return {}

    def execute(self, cr, uid, ids, context=None):
        self.execute_simple(cr, uid, ids, context)
        super(account_installer, self).execute(cr, uid, ids, context=context)

    def execute_simple(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        fy_obj = self.pool.get('account.fiscalyear')
        for res in self.read(cr, uid, ids, context=context):
            if 'date_start' in res and 'date_stop' in res:
                f_ids = fy_obj.search(cr, uid, [('date_start', '<=', res['date_start']), ('date_stop', '>=', res['date_stop']), ('company_id', '=', res['company_id'][0])], context=context)
                if not f_ids:
                    name = code = res['date_start'][:4]
                    if int(name) != int(res['date_stop'][:4]):
                        name = res['date_start'][:4] +'-'+ res['date_stop'][:4]
                        code = res['date_start'][2:4] +'-'+ res['date_stop'][2:4]
                    vals = {
                        'name': name,
                        'code': code,
                        'date_start': res['date_start'],
                        'date_stop': res['date_stop'],
                        'company_id': res['company_id'][0]
                    }
                    fiscal_id = fy_obj.create(cr, uid, vals, context=context)
                    if res['period'] == 'month':
                        fy_obj.create_period(cr, uid, [fiscal_id])
                    elif res['period'] == '3months':
                        fy_obj.create_period3(cr, uid, [fiscal_id])

    def modules_to_install(self, cr, uid, ids, context=None):
        modules = super(account_installer, self).modules_to_install(
            cr, uid, ids, context=context)
        chart = self.read(cr, uid, ids, ['charts'],
                          context=context)[0]['charts']
        _logger.debug('Installing chart of accounts %s', chart)
        return modules | set([chart])

account_installer()

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-today OpenERP SA (<http://www.openerp.com>)
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from openerp.addons.base_status.base_state import base_state
import crm
from datetime import datetime
from openerp.osv import fields, osv
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
from openerp.tools.translate import _

class crm_phonecall(base_state, osv.osv):
    """ Model for CRM phonecalls """
    _name = "crm.phonecall"
    _description = "Phonecall"
    _order = "id desc"
    _inherit = ['mail.thread']
    _columns = {
        # base_state required fields
        'date_action_last': fields.datetime('Last Action', readonly=1),
        'date_action_next': fields.datetime('Next Action', readonly=1),
        'create_date': fields.datetime('Creation Date' , readonly=True),
        'section_id': fields.many2one('crm.case.section', 'Sales Team', \
                        select=True, help='Sales team to which Case belongs to.'),
        'user_id': fields.many2one('res.users', 'Responsible'),
        'partner_id': fields.many2one('res.partner', 'Contact'),
        'company_id': fields.many2one('res.company', 'Company'),
        'description': fields.text('Description'),
        'state': fields.selection([ ('draft', 'Draft'),
                                    ('open', 'Confirmed'),
                                    ('pending', 'Not Held'),
                                    ('cancel', 'Cancelled'),
                                    ('done', 'Held'),],
                        string='Status', size=16, readonly=True, track_visibility='onchange',
                        help='The status is set to \'Todo\', when a case is created.\
                                If the case is in progress the status is set to \'Open\'.\
                                When the call is over, the status is set to \'Held\'.\
                                If the call needs to be done then the status is set to \'Not Held\'.'),
        'email_from': fields.char('Email', size=128, help="These people will receive email."),
        'date_open': fields.datetime('Opened', readonly=True),
        # phonecall fields
        'name': fields.char('Call Summary', size=64, required=True),
        'active': fields.boolean('Active', required=False),
        'duration': fields.float('Duration', help="Duration in Minutes"),
        'categ_id': fields.many2one('crm.case.categ', 'Category', \
                        domain="['|',('section_id','=',section_id),('section_id','=',False),\
                        ('object_id.model', '=', 'crm.phonecall')]"),
        'partner_phone': fields.char('Phone', size=32),
        'partner_mobile': fields.char('Mobile', size=32),
        'priority': fields.selection(crm.AVAILABLE_PRIORITIES, 'Priority'),
        'date_closed': fields.datetime('Closed', readonly=True),
        'date': fields.datetime('Date'),
        'opportunity_id': fields.many2one ('crm.lead', 'Lead/Opportunity'),
    }

    def _get_default_state(self, cr, uid, context=None):
        if context and context.get('default_state', False):
            return context.get('default_state')
        return 'open'

    _defaults = {
        'date': fields.datetime.now,
        'priority': crm.AVAILABLE_PRIORITIES[2][0],
        'state':  _get_default_state,
        'user_id': lambda self,cr,uid,ctx: uid,
        'active': 1
    }

    def case_close(self, cr, uid, ids, context=None):
        """ Overrides close for crm_case for setting duration """
        res = True
        for phone in self.browse(cr, uid, ids, context=context):
            phone_id = phone.id
            data = {}
            if phone.duration <=0:
                duration = datetime.now() - datetime.strptime(phone.date, DEFAULT_SERVER_DATETIME_FORMAT)
                data['duration'] = duration.seconds/float(60)
            res = super(crm_phonecall, self).case_close(cr, uid, [phone_id], context=context)
            self.write(cr, uid, [phone_id], data, context=context)
        return res

    def case_reset(self, cr, uid, ids, context=None):
        """Resets case as Todo
        """
        res = super(crm_phonecall, self).case_reset(cr, uid, ids, context)
        self.write(cr, uid, ids, {'duration': 0.0, 'state':'open'}, context=context)
        return res

    def schedule_another_phonecall(self, cr, uid, ids, schedule_time, call_summary, \
                    user_id=False, section_id=False, categ_id=False, action='schedule', context=None):
        """
        action :('schedule','Schedule a call'), ('log','Log a call')
        """
        model_data = self.pool.get('ir.model.data')
        phonecall_dict = {}
        if not categ_id:
            res_id = model_data._get_id(cr, uid, 'crm', 'categ_phone2')
            if res_id:
                categ_id = model_data.browse(cr, uid, res_id, context=context).res_id
        for call in self.browse(cr, uid, ids, context=context):
            if not section_id:
                section_id = call.section_id and call.section_id.id or False
            if not user_id:
                user_id = call.user_id and call.user_id.id or False
            if not schedule_time:
                schedule_time = call.date
            vals = {
                    'name' : call_summary,
                    'user_id' : user_id or False,
                    'categ_id' : categ_id or False,
                    'description' : call.description or False,
                    'date' : schedule_time,
                    'section_id' : section_id or False,
                    'partner_id': call.partner_id and call.partner_id.id or False,
                    'partner_phone' : call.partner_phone,
                    'partner_mobile' : call.partner_mobile,
                    'priority': call.priority,
            }
            new_id = self.create(cr, uid, vals, context=context)
            if action == 'log':
                self.case_close(cr, uid, [new_id])
            phonecall_dict[call.id] = new_id
        return phonecall_dict

    def _call_create_partner(self, cr, uid, phonecall, context=None):
        partner = self.pool.get('res.partner')
        partner_id = partner.create(cr, uid, {
                    'name': phonecall.name,
                    'user_id': phonecall.user_id.id,
                    'comment': phonecall.description,
                    'address': []
        })
        return partner_id

    def on_change_opportunity(self, cr, uid, ids, opportunity_id, context=None):
        values = {}
        if opportunity_id:
            opportunity = self.pool.get('crm.lead').browse(cr, uid, opportunity_id, context=context)
            values = {
                'section_id' : opportunity.section_id and opportunity.section_id.id or False,
                'partner_phone' : opportunity.phone,
                'partner_mobile' : opportunity.mobile,
                'partner_id' : opportunity.partner_id and opportunity.partner_id.id or False,
            }
        return {'value' : values}

    def _call_set_partner(self, cr, uid, ids, partner_id, context=None):
        write_res = self.write(cr, uid, ids, {'partner_id' : partner_id}, context=context)
        self._call_set_partner_send_note(cr, uid, ids, context)
        return write_res

    def _call_create_partner_address(self, cr, uid, phonecall, partner_id, context=None):
        address = self.pool.get('res.partner')
        return address.create(cr, uid, {
                    'parent_id': partner_id,
                    'name': phonecall.name,
                    'phone': phonecall.partner_phone,
        })

    def handle_partner_assignation(self, cr, uid, ids, action='create', partner_id=False, context=None):
        """
        Handle partner assignation during a lead conversion.
        if action is 'create', create new partner with contact and assign lead to new partner_id.
        otherwise assign lead to specified partner_id

        :param list ids: phonecalls ids to process
        :param string action: what has to be done regarding partners (create it, assign an existing one, or nothing)
        :param int partner_id: partner to assign if any
        :return dict: dictionary organized as followed: {lead_id: partner_assigned_id}
        """
        #TODO this is a duplication of the handle_partner_assignation method of crm_lead
        partner_ids = {}
        # If a partner_id is given, force this partner for all elements
        force_partner_id = partner_id
        for call in self.browse(cr, uid, ids, context=context):
            # If the action is set to 'create' and no partner_id is set, create a new one
            if action == 'create':
                partner_id = force_partner_id or self._call_create_partner(cr, uid, call, context=context)
                self._call_create_partner_address(cr, uid, call, partner_id, context=context)
            self._call_set_partner(cr, uid, [call.id], partner_id, context=context)
            partner_ids[call.id] = partner_id
        return partner_ids

    def redirect_phonecall_view(self, cr, uid, phonecall_id, context=None):
        model_data = self.pool.get('ir.model.data')
        # Select the view
        tree_view = model_data.get_object_reference(cr, uid, 'crm', 'crm_case_phone_tree_view')
        form_view = model_data.get_object_reference(cr, uid, 'crm', 'crm_case_phone_form_view')
        search_view = model_data.get_object_reference(cr, uid, 'crm', 'view_crm_case_phonecalls_filter')
        value = {
                'name': _('Phone Call'),
                'view_type': 'form',
                'view_mode': 'tree,form',
                'res_model': 'crm.phonecall',
                'res_id' : int(phonecall_id),
                'views': [(form_view and form_view[1] or False, 'form'), (tree_view and tree_view[1] or False, 'tree'), (False, 'calendar')],
                'type': 'ir.actions.act_window',
                'search_view_id': search_view and search_view[1] or False,
        }
        return value

    def convert_opportunity(self, cr, uid, ids, opportunity_summary=False, partner_id=False, planned_revenue=0.0, probability=0.0, context=None):
        partner = self.pool.get('res.partner')
        opportunity = self.pool.get('crm.lead')
        opportunity_dict = {}
        default_contact = False
        for call in self.browse(cr, uid, ids, context=context):
            if not partner_id:
                partner_id = call.partner_id and call.partner_id.id or False
            if partner_id:
                address_id = partner.address_get(cr, uid, [partner_id])['default']
                if address_id:
                    default_contact = partner.browse(cr, uid, address_id, context=context)
            opportunity_id = opportunity.create(cr, uid, {
                            'name': opportunity_summary or call.name,
                            'planned_revenue': planned_revenue,
                            'probability': probability,
                            'partner_id': partner_id or False,
                            'mobile': default_contact and default_contact.mobile,
                            'section_id': call.section_id and call.section_id.id or False,
                            'description': call.description or False,
                            'priority': call.priority,
                            'type': 'opportunity',
                            'phone': call.partner_phone or False,
                            'email_from': default_contact and default_contact.email,
                        })
            vals = {
                    'partner_id': partner_id,
                    'opportunity_id' : opportunity_id,
            }
            self.write(cr, uid, [call.id], vals)
            self.case_close(cr, uid, [call.id])
            opportunity.case_open(cr, uid, [opportunity_id])
            opportunity_dict[call.id] = opportunity_id
        return opportunity_dict

    def action_make_meeting(self, cr, uid, ids, context=None):
        """
        Open meeting's calendar view to schedule a meeting on current phonecall.
        :return dict: dictionary value for created meeting view
        """
        phonecall = self.browse(cr, uid, ids[0], context)
        res = self.pool.get('ir.actions.act_window').for_xml_id(cr, uid, 'base_calendar', 'action_crm_meeting', context)
        res['context'] = {
            'default_phonecall_id': phonecall.id,
            'default_partner_id': phonecall.partner_id and phonecall.partner_id.id or False,
            'default_user_id': uid,
            'default_email_from': phonecall.email_from,
            'default_state': 'open',
            'default_name': phonecall.name,
        }
        return res

    def action_button_convert2opportunity(self, cr, uid, ids, context=None):
        """
        Convert a phonecall into an opp and then redirect to the opp view.

        :param list ids: list of calls ids to convert (typically contains a single id)
        :return dict: containing view information
        """
        if len(ids) != 1:
            raise osv.except_osv(_('Warning!'),_('It\'s only possible to convert one phonecall at a time.'))

        opportunity_dict = self.convert_opportunity(cr, uid, ids, context=context)
        return self.pool.get('crm.lead').redirect_opportunity_view(cr, uid, opportunity_dict[ids[0]], context)

    # ----------------------------------------
    # OpenChatter
    # ----------------------------------------

    def _call_set_partner_send_note(self, cr, uid, ids, context=None):
        return self.message_post(cr, uid, ids, body=_("Partner has been <b>created</b>."), context=context)

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
<commit_msg>[IMP] remove unused warning given while Schedule a meeting from phone call, select Attendee and Save. so remve defalt state value.<commit_after># -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-today OpenERP SA (<http://www.openerp.com>)
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from openerp.addons.base_status.base_state import base_state
import crm
from datetime import datetime
from openerp.osv import fields, osv
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
from openerp.tools.translate import _

class crm_phonecall(base_state, osv.osv):
    """ Model for CRM phonecalls """
    _name = "crm.phonecall"
    _description = "Phonecall"
    _order = "id desc"
    _inherit = ['mail.thread']
    _columns = {
        # base_state required fields
        'date_action_last': fields.datetime('Last Action', readonly=1),
        'date_action_next': fields.datetime('Next Action', readonly=1),
        'create_date': fields.datetime('Creation Date' , readonly=True),
        'section_id': fields.many2one('crm.case.section', 'Sales Team', \
                        select=True, help='Sales team to which Case belongs to.'),
        'user_id': fields.many2one('res.users', 'Responsible'),
        'partner_id': fields.many2one('res.partner', 'Contact'),
        'company_id': fields.many2one('res.company', 'Company'),
        'description': fields.text('Description'),
        'state': fields.selection([ ('draft', 'Draft'),
                                    ('open', 'Confirmed'),
                                    ('pending', 'Not Held'),
                                    ('cancel', 'Cancelled'),
                                    ('done', 'Held'),],
                        string='Status', size=16, readonly=True, track_visibility='onchange',
                        help='The status is set to \'Todo\', when a case is created.\
                                If the case is in progress the status is set to \'Open\'.\
                                When the call is over, the status is set to \'Held\'.\
                                If the call needs to be done then the status is set to \'Not Held\'.'),
        'email_from': fields.char('Email', size=128, help="These people will receive email."),
        'date_open': fields.datetime('Opened', readonly=True),
        # phonecall fields
        'name': fields.char('Call Summary', size=64, required=True),
        'active': fields.boolean('Active', required=False),
        'duration': fields.float('Duration', help="Duration in Minutes"),
        'categ_id': fields.many2one('crm.case.categ', 'Category', \
                        domain="['|',('section_id','=',section_id),('section_id','=',False),\
                        ('object_id.model', '=', 'crm.phonecall')]"),
        'partner_phone': fields.char('Phone', size=32),
        'partner_mobile': fields.char('Mobile', size=32),
        'priority': fields.selection(crm.AVAILABLE_PRIORITIES, 'Priority'),
        'date_closed': fields.datetime('Closed', readonly=True),
        'date': fields.datetime('Date'),
        'opportunity_id': fields.many2one ('crm.lead', 'Lead/Opportunity'),
    }

    def _get_default_state(self, cr, uid, context=None):
        if context and context.get('default_state', False):
            return context.get('default_state')
        return 'open'

    _defaults = {
        'date': fields.datetime.now,
        'priority': crm.AVAILABLE_PRIORITIES[2][0],
        'state':  _get_default_state,
        'user_id': lambda self,cr,uid,ctx: uid,
        'active': 1
    }

    def case_close(self, cr, uid, ids, context=None):
        """ Overrides close for crm_case for setting duration """
        res = True
        for phone in self.browse(cr, uid, ids, context=context):
            phone_id = phone.id
            data = {}
            if phone.duration <=0:
                duration = datetime.now() - datetime.strptime(phone.date, DEFAULT_SERVER_DATETIME_FORMAT)
                data['duration'] = duration.seconds/float(60)
            res = super(crm_phonecall, self).case_close(cr, uid, [phone_id], context=context)
            self.write(cr, uid, [phone_id], data, context=context)
        return res

    def case_reset(self, cr, uid, ids, context=None):
        """Resets case as Todo
        """
        res = super(crm_phonecall, self).case_reset(cr, uid, ids, context)
        self.write(cr, uid, ids, {'duration': 0.0, 'state':'open'}, context=context)
        return res

    def schedule_another_phonecall(self, cr, uid, ids, schedule_time, call_summary, \
                    user_id=False, section_id=False, categ_id=False, action='schedule', context=None):
        """
        action :('schedule','Schedule a call'), ('log','Log a call')
        """
        model_data = self.pool.get('ir.model.data')
        phonecall_dict = {}
        if not categ_id:
            res_id = model_data._get_id(cr, uid, 'crm', 'categ_phone2')
            if res_id:
                categ_id = model_data.browse(cr, uid, res_id, context=context).res_id
        for call in self.browse(cr, uid, ids, context=context):
            if not section_id:
                section_id = call.section_id and call.section_id.id or False
            if not user_id:
                user_id = call.user_id and call.user_id.id or False
            if not schedule_time:
                schedule_time = call.date
            vals = {
                    'name' : call_summary,
                    'user_id' : user_id or False,
                    'categ_id' : categ_id or False,
                    'description' : call.description or False,
                    'date' : schedule_time,
                    'section_id' : section_id or False,
                    'partner_id': call.partner_id and call.partner_id.id or False,
                    'partner_phone' : call.partner_phone,
                    'partner_mobile' : call.partner_mobile,
                    'priority': call.priority,
            }
            new_id = self.create(cr, uid, vals, context=context)
            if action == 'log':
                self.case_close(cr, uid, [new_id])
            phonecall_dict[call.id] = new_id
        return phonecall_dict

    def _call_create_partner(self, cr, uid, phonecall, context=None):
        partner = self.pool.get('res.partner')
        partner_id = partner.create(cr, uid, {
                    'name': phonecall.name,
                    'user_id': phonecall.user_id.id,
                    'comment': phonecall.description,
                    'address': []
        })
        return partner_id

    def on_change_opportunity(self, cr, uid, ids, opportunity_id, context=None):
        values = {}
        if opportunity_id:
            opportunity = self.pool.get('crm.lead').browse(cr, uid, opportunity_id, context=context)
            values = {
                'section_id' : opportunity.section_id and opportunity.section_id.id or False,
                'partner_phone' : opportunity.phone,
                'partner_mobile' : opportunity.mobile,
                'partner_id' : opportunity.partner_id and opportunity.partner_id.id or False,
            }
        return {'value' : values}

    def _call_set_partner(self, cr, uid, ids, partner_id, context=None):
        write_res = self.write(cr, uid, ids, {'partner_id' : partner_id}, context=context)
        self._call_set_partner_send_note(cr, uid, ids, context)
        return write_res

    def _call_create_partner_address(self, cr, uid, phonecall, partner_id, context=None):
        address = self.pool.get('res.partner')
        return address.create(cr, uid, {
                    'parent_id': partner_id,
                    'name': phonecall.name,
                    'phone': phonecall.partner_phone,
        })

    def handle_partner_assignation(self, cr, uid, ids, action='create', partner_id=False, context=None):
        """
        Handle partner assignation during a lead conversion.
        if action is 'create', create new partner with contact and assign lead to new partner_id.
        otherwise assign lead to specified partner_id

        :param list ids: phonecalls ids to process
        :param string action: what has to be done regarding partners (create it, assign an existing one, or nothing)
        :param int partner_id: partner to assign if any
        :return dict: dictionary organized as followed: {lead_id: partner_assigned_id}
        """
        #TODO this is a duplication of the handle_partner_assignation method of crm_lead
        partner_ids = {}
        # If a partner_id is given, force this partner for all elements
        force_partner_id = partner_id
        for call in self.browse(cr, uid, ids, context=context):
            # If the action is set to 'create' and no partner_id is set, create a new one
            if action == 'create':
                partner_id = force_partner_id or self._call_create_partner(cr, uid, call, context=context)
                self._call_create_partner_address(cr, uid, call, partner_id, context=context)
            self._call_set_partner(cr, uid, [call.id], partner_id, context=context)
            partner_ids[call.id] = partner_id
        return partner_ids

    def redirect_phonecall_view(self, cr, uid, phonecall_id, context=None):
        model_data = self.pool.get('ir.model.data')
        # Select the view
        tree_view = model_data.get_object_reference(cr, uid, 'crm', 'crm_case_phone_tree_view')
        form_view = model_data.get_object_reference(cr, uid, 'crm', 'crm_case_phone_form_view')
        search_view = model_data.get_object_reference(cr, uid, 'crm', 'view_crm_case_phonecalls_filter')
        value = {
                'name': _('Phone Call'),
                'view_type': 'form',
                'view_mode': 'tree,form',
                'res_model': 'crm.phonecall',
                'res_id' : int(phonecall_id),
                'views': [(form_view and form_view[1] or False, 'form'), (tree_view and tree_view[1] or False, 'tree'), (False, 'calendar')],
                'type': 'ir.actions.act_window',
                'search_view_id': search_view and search_view[1] or False,
        }
        return value

    def convert_opportunity(self, cr, uid, ids, opportunity_summary=False, partner_id=False, planned_revenue=0.0, probability=0.0, context=None):
        partner = self.pool.get('res.partner')
        opportunity = self.pool.get('crm.lead')
        opportunity_dict = {}
        default_contact = False
        for call in self.browse(cr, uid, ids, context=context):
            if not partner_id:
                partner_id = call.partner_id and call.partner_id.id or False
            if partner_id:
                address_id = partner.address_get(cr, uid, [partner_id])['default']
                if address_id:
                    default_contact = partner.browse(cr, uid, address_id, context=context)
            opportunity_id = opportunity.create(cr, uid, {
                            'name': opportunity_summary or call.name,
                            'planned_revenue': planned_revenue,
                            'probability': probability,
                            'partner_id': partner_id or False,
                            'mobile': default_contact and default_contact.mobile,
                            'section_id': call.section_id and call.section_id.id or False,
                            'description': call.description or False,
                            'priority': call.priority,
                            'type': 'opportunity',
                            'phone': call.partner_phone or False,
                            'email_from': default_contact and default_contact.email,
                        })
            vals = {
                    'partner_id': partner_id,
                    'opportunity_id' : opportunity_id,
            }
            self.write(cr, uid, [call.id], vals)
            self.case_close(cr, uid, [call.id])
            opportunity.case_open(cr, uid, [opportunity_id])
            opportunity_dict[call.id] = opportunity_id
        return opportunity_dict

    def action_make_meeting(self, cr, uid, ids, context=None):
        """
        Open meeting's calendar view to schedule a meeting on current phonecall.
        :return dict: dictionary value for created meeting view
        """
        phonecall = self.browse(cr, uid, ids[0], context)
        res = self.pool.get('ir.actions.act_window').for_xml_id(cr, uid, 'base_calendar', 'action_crm_meeting', context)
        res['context'] = {
            'default_phonecall_id': phonecall.id,
            'default_partner_id': phonecall.partner_id and phonecall.partner_id.id or False,
            'default_user_id': uid,
            'default_email_from': phonecall.email_from,
            'default_name': phonecall.name,
        }
        return res

    def action_button_convert2opportunity(self, cr, uid, ids, context=None):
        """
        Convert a phonecall into an opp and then redirect to the opp view.

        :param list ids: list of calls ids to convert (typically contains a single id)
        :return dict: containing view information
        """
        if len(ids) != 1:
            raise osv.except_osv(_('Warning!'),_('It\'s only possible to convert one phonecall at a time.'))

        opportunity_dict = self.convert_opportunity(cr, uid, ids, context=context)
        return self.pool.get('crm.lead').redirect_opportunity_view(cr, uid, opportunity_dict[ids[0]], context)

    # ----------------------------------------
    # OpenChatter
    # ----------------------------------------

    def _call_set_partner_send_note(self, cr, uid, ids, context=None):
        return self.message_post(cr, uid, ids, body=_("Partner has been <b>created</b>."), context=context)

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import api, fields, models, _

class BaseLanguageInstall(models.TransientModel):
    _name = "base.language.install"
    _description = "Install Language"

    @api.model
    def _default_language(self):
        """ Display the selected language when using the 'Update Terms' action
            from the language list view
        """
        if self._context.get('active_model') == 'res.lang':
            lang = self.env['res.lang'].browse(self._context.get('active_id'))
            return lang.code
        return False

    @api.model
    def _get_languages(self):
        return self.env['res.lang'].get_available()

    lang = fields.Selection(_get_languages, string='Language', required=True,
                            default=_default_language)
    overwrite = fields.Boolean('Overwrite Existing Terms',
                               help="If you check this box, your customized translations will be overwritten and replaced by the official ones.")
    state = fields.Selection([('init', 'init'), ('done', 'done')],
                             string='Status', readonly=True, default='init')

    @api.multi
    def lang_install(self):
        self.ensure_one()
        mods = self.env['ir.module.module'].search([('state', '=', 'installed')])
        mods.with_context(overwrite=self.overwrite)._update_translations(self.lang)
        self.state = 'done'
        return {
            'name': _('Language Pack'),
            'view_type': 'form',
            'view_mode': 'form',
            'view_id': False,
            'res_model': 'base.language.install',
            'domain': [],
            'context': dict(self._context, active_ids=self.ids),
            'type': 'ir.actions.act_window',
            'target': 'new',
            'res_id': self.id,
        }

    def reload(self):
        return {
            'type': 'ir.actions.client',
            'tag': 'reload',
        }
<commit_msg>[FIX] base: fix rte translator timeout<commit_after># -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import api, fields, models, _

class BaseLanguageInstall(models.TransientModel):
    _name = "base.language.install"
    _description = "Install Language"

    @api.model
    def _default_language(self):
        """ Display the selected language when using the 'Update Terms' action
            from the language list view
        """
        if self._context.get('active_model') == 'res.lang':
            lang = self.env['res.lang'].browse(self._context.get('active_id'))
            return lang.code
        return False

    @api.model
    def _get_languages(self):
        return self.env['res.lang'].get_available()

    lang = fields.Selection(_get_languages, string='Language', required=True,
                            default=_default_language)
    overwrite = fields.Boolean('Overwrite Existing Terms',
                               help="If you check this box, your customized translations will be overwritten and replaced by the official ones.")
    state = fields.Selection([('init', 'init'), ('done', 'done')],
                             string='Status', readonly=True, default='init')

    @api.multi
    def lang_install(self):
        self.ensure_one()
        mods = self.env['ir.module.module'].search([('state', '=', 'installed')])
        mods.with_context(overwrite=self.overwrite)._update_translations(self.lang)
        self.state = 'done'
        self.env.cr.execute('ANALYZE ir_translation')

        return {
            'name': _('Language Pack'),
            'view_type': 'form',
            'view_mode': 'form',
            'view_id': False,
            'res_model': 'base.language.install',
            'domain': [],
            'context': dict(self._context, active_ids=self.ids),
            'type': 'ir.actions.act_window',
            'target': 'new',
            'res_id': self.id,
        }

    def reload(self):
        return {
            'type': 'ir.actions.client',
            'tag': 'reload',
        }
<|endoftext|>


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

import copy
import mock

from openstackclient.common import exceptions
from openstackclient.network.v2 import network
from openstackclient.tests import fakes
from openstackclient.tests.identity.v2_0 import fakes as identity_fakes_v2
from openstackclient.tests.identity.v3 import fakes as identity_fakes_v3
from openstackclient.tests.network import common
from openstackclient.tests.network.v2 import fakes as network_fakes

RESOURCE = 'network'
RESOURCES = 'networks'
FAKE_ID = 'iditty'
FAKE_NAME = 'noo'
FAKE_PROJECT = 'yaa'
RECORD = {
    'id': FAKE_ID,
    'name': FAKE_NAME,
    'admin_state_up': True,
    'router:external': True,
    'status': 'ACTIVE',
    'subnets': ['a', 'b'],
    'tenant_id': FAKE_PROJECT,
}
RESPONSE = {RESOURCE: copy.deepcopy(RECORD)}
FILTERED = [
    (
        'id',
        'name',
        'project_id',
        'router_type',
        'state',
        'status',
        'subnets',
    ),
    (
        FAKE_ID,
        FAKE_NAME,
        FAKE_PROJECT,
        'External',
        'UP',
        'ACTIVE',
        'a, b',
    ),
]

class TestNetwork(network_fakes.TestNetworkV2):

    def setUp(self):
        super(TestNetwork, self).setUp()

        # Get a shortcut to the network client
        self.network = self.app.client_manager.network

        # Get a shortcut to the APIManager
        self.api = self.app.client_manager.network.api

class TestCreateNetworkIdentityV3(TestNetwork):

    def setUp(self):
        super(TestCreateNetworkIdentityV3, self).setUp()

        self.new_network = mock.Mock(return_value=copy.deepcopy(RESPONSE))
        self.network.create_network = self.new_network

        # Get the command object to test
        self.cmd = network.CreateNetwork(self.app, self.namespace)

        # Set identity client v3. And get a shortcut to Identity client.
        identity_client = identity_fakes_v3.FakeIdentityv3Client(
            endpoint=fakes.AUTH_URL,
            token=fakes.AUTH_TOKEN,
        )
        self.app.client_manager.identity = identity_client
        self.identity = self.app.client_manager.identity

        # Get a shortcut to the ProjectManager Mock
        self.projects_mock = self.identity.projects
        self.projects_mock.get.return_value = fakes.FakeResource(
            None,
            copy.deepcopy(identity_fakes_v3.PROJECT),
            loaded=True,
        )

        # Get a shortcut to the DomainManager Mock
        self.domains_mock = self.identity.domains
        self.domains_mock.get.return_value = fakes.FakeResource(
            None,
            copy.deepcopy(identity_fakes_v3.DOMAIN),
            loaded=True,
        )

    def test_create_no_options(self):
        arglist = [
            FAKE_NAME,
        ]
        verifylist = [
            ('name', FAKE_NAME),
            ('admin_state', True),
            ('shared', None),
            ('project', None),
        ]

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)
        result = list(self.cmd.take_action(parsed_args))

        self.network.create_network.assert_called_with({
            RESOURCE: {
                'admin_state_up': True,
                'name': FAKE_NAME,
            }
        })
        self.assertEqual(FILTERED, result)

    def test_create_all_options(self):
        arglist = [
            "--disable",
            "--share",
            "--project", identity_fakes_v3.project_name,
            "--project-domain", identity_fakes_v3.domain_name,
            FAKE_NAME,
        ]
        verifylist = [
            ('admin_state', False),
            ('shared', True),
            ('project', identity_fakes_v3.project_name),
            ('project_domain', identity_fakes_v3.domain_name),
            ('name', FAKE_NAME),
        ]

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)
        result = list(self.cmd.take_action(parsed_args))

        self.network.create_network.assert_called_with({
            RESOURCE: {
                'admin_state_up': False,
                'name': FAKE_NAME,
                'shared': True,
                'tenant_id': identity_fakes_v3.project_id,
            }
        })
        self.assertEqual(FILTERED, result)

    def test_create_other_options(self):
        arglist = [
            "--enable",
            "--no-share",
            FAKE_NAME,
        ]
        verifylist = [
            ('admin_state', True),
            ('shared', False),
            ('name', FAKE_NAME),
        ]

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)
        result = list(self.cmd.take_action(parsed_args))

        self.network.create_network.assert_called_with({
            RESOURCE: {
                'admin_state_up': True,
                'name': FAKE_NAME,
                'shared': False,
            }
        })
        self.assertEqual(FILTERED, result)

class TestCreateNetworkIdentityV2(TestNetwork):

    def setUp(self):
        super(TestCreateNetworkIdentityV2, self).setUp()

        self.new_network = mock.Mock(return_value=copy.deepcopy(RESPONSE))
        self.network.create_network = self.new_network

        # Get the command object to test
        self.cmd = network.CreateNetwork(self.app, self.namespace)

        # Set identity client v2. And get a shortcut to Identity client.
        identity_client = identity_fakes_v2.FakeIdentityv2Client(
            endpoint=fakes.AUTH_URL,
            token=fakes.AUTH_TOKEN,
        )
        self.app.client_manager.identity = identity_client
        self.identity = self.app.client_manager.identity

        # Get a shortcut to the ProjectManager Mock
        self.projects_mock = self.identity.tenants
        self.projects_mock.get.return_value = fakes.FakeResource(
            None,
            copy.deepcopy(identity_fakes_v2.PROJECT),
            loaded=True,
        )

        # There is no DomainManager Mock in fake identity v2.

    def test_create_with_project_identityv2(self):
        arglist = [
            "--project", identity_fakes_v2.project_name,
            FAKE_NAME,
        ]
        verifylist = [
            ('admin_state', True),
            ('shared', None),
            ('name', FAKE_NAME),
            ('project', identity_fakes_v2.project_name),
        ]

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)
        result = list(self.cmd.take_action(parsed_args))

        self.network.create_network.assert_called_with({
            RESOURCE: {
                'admin_state_up': True,
                'name': FAKE_NAME,
                'tenant_id': identity_fakes_v2.project_id,
            }
        })
        self.assertEqual(FILTERED, result)

    def test_create_with_domain_identityv2(self):
        arglist = [
            "--project", identity_fakes_v3.project_name,
            "--project-domain", identity_fakes_v3.domain_name,
            FAKE_NAME,
        ]
        verifylist = [
            ('admin_state', True),
            ('shared', None),
            ('project', identity_fakes_v3.project_name),
            ('project_domain', identity_fakes_v3.domain_name),
            ('name', FAKE_NAME),
        ]

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)

        self.assertRaises(
            AttributeError,
            self.cmd.take_action,
            parsed_args,
        )

class TestDeleteNetwork(TestNetwork):

    def setUp(self):
        super(TestDeleteNetwork, self).setUp()

        self.network.delete_network = mock.Mock(
            return_value=None
        )

        self.network.list_networks = mock.Mock(
            return_value={RESOURCES: [copy.deepcopy(RECORD)]}
        )

        # Get the command object to test
        self.cmd = network.DeleteNetwork(self.app, self.namespace)

    def test_delete(self):
        arglist = [
            FAKE_NAME,
        ]
        verifylist = [
            ('networks', [FAKE_NAME]),
        ]

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)
        result = self.cmd.take_action(parsed_args)

        self.network.delete_network.assert_called_with(FAKE_ID)
        self.assertEqual(None, result)

@mock.patch(
    'openstackclient.api.network_v2.APIv2.network_list'
)
class TestListNetwork(TestNetwork):

    columns = [
        'ID',
        'Name',
        'Subnets'
    ]
    columns_long = [
        'ID',
        'Name',
        'Status',
        'Project',
        'State',
        'Shared',
        'Subnets',
        'Network Type',
        'Router Type',
    ]

    data = [
        (FAKE_ID, FAKE_NAME, 'a, b'),
        (FAKE_ID, FAKE_NAME, 'a, b'),
    ]
    data_long = [
        (FAKE_ID, FAKE_NAME, 'ACTIVE', FAKE_PROJECT,
         'UP', '', 'a, b', '', 'External'),
        (FAKE_ID, FAKE_NAME, 'ACTIVE', FAKE_PROJECT,
         'UP', '', 'a, b', '', 'External'),
    ]

    def setUp(self):
        super(TestListNetwork, self).setUp()

        # Get the command object to test
        self.cmd = network.ListNetwork(self.app, self.namespace)

        self.NETWORK_LIST = [
            copy.deepcopy(RECORD),
            copy.deepcopy(RECORD),
        ]

    def test_network_list_no_options(self, network_list):
        network_list.return_value = self.NETWORK_LIST

        arglist = []
        verifylist = [
            ('external', False),
            ('long', False),
        ]
        parsed_args = self.check_parser(self.cmd, arglist, verifylist)

        # DisplayCommandBase.take_action() returns two tuples
        columns, data = self.cmd.take_action(parsed_args)

        # Set expected values
        network_list.assert_called_with(
            external=False,
        )

        self.assertEqual(tuple(self.columns), columns)
        self.assertEqual(self.data, list(data))

    def test_list_external(self, network_list):
        network_list.return_value = self.NETWORK_LIST

        arglist = [
            '--external',
        ]
        verifylist = [
            ('external', True),
            ('long', False),
        ]
        parsed_args = self.check_parser(self.cmd, arglist, verifylist)

        # DisplayCommandBase.take_action() returns two tuples
        columns, data = self.cmd.take_action(parsed_args)

        # Set expected values
        network_list.assert_called_with(
            external=True,
        )

        self.assertEqual(tuple(self.columns), columns)
        self.assertEqual(self.data, list(data))

    def test_network_list_long(self, network_list):
        network_list.return_value = self.NETWORK_LIST

        arglist = [
            '--long',
        ]
        verifylist = [
            ('long', True),
            ('external', False),
        ]
        parsed_args = self.check_parser(self.cmd, arglist, verifylist)

        # DisplayCommandBase.take_action() returns two tuples
        columns, data = self.cmd.take_action(parsed_args)

        # Set expected values
        network_list.assert_called_with(
            external=False,
        )

        self.assertEqual(columns, tuple(self.columns_long))
        self.assertEqual(self.data_long, list(data))

class TestSetNetwork(TestNetwork):

    def setUp(self):
        super(TestSetNetwork, self).setUp()

        self.network.update_network = mock.Mock(
            return_value=None
        )

        self.network.list_networks = mock.Mock(
            return_value={RESOURCES: [copy.deepcopy(RECORD)]}
        )

        self.cmd = network.SetNetwork(self.app, self.namespace)

    def test_set_this(self):
        arglist = [
            FAKE_NAME,
            '--enable',
            '--name', 'noob',
            '--share',
        ]
        verifylist = [
            ('identifier', FAKE_NAME),
            ('admin_state', True),
            ('name', 'noob'),
            ('shared', True),
        ]

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)
        result = self.cmd.take_action(parsed_args)

        exp = {'admin_state_up': True, 'name': 'noob', 'shared': True}
        exp_record = {RESOURCE: exp}
        self.network.update_network.assert_called_with(FAKE_ID, exp_record)
        self.assertEqual(None, result)

    def test_set_that(self):
        arglist = [
            FAKE_NAME,
            '--disable',
            '--no-share',
        ]
        verifylist = [
            ('identifier', FAKE_NAME),
            ('admin_state', False),
            ('shared', False),
        ]

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)
        result = self.cmd.take_action(parsed_args)

        exp = {'admin_state_up': False, 'shared': False}
        exp_record = {RESOURCE: exp}
        self.network.update_network.assert_called_with(FAKE_ID, exp_record)
        self.assertEqual(None, result)

    def test_set_nothing(self):
        arglist = [FAKE_NAME, ]
        verifylist = [('identifier', FAKE_NAME), ]

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)
        self.assertRaises(exceptions.CommandError, self.cmd.take_action,
                          parsed_args)

@mock.patch(
    'openstackclient.api.network_v2.APIv2.find_attr'
)
class TestShowNetwork(common.TestNetworkBase):

    def setUp(self):
        super(TestShowNetwork, self).setUp()

        # Get the command object to test
        self.cmd = network.ShowNetwork(self.app, self.namespace)

        self.NETWORK_ITEM = copy.deepcopy(RECORD)

    def test_show_no_options(self, n_mock):
        arglist = [
            FAKE_NAME,
        ]
        verifylist = [
            ('identifier', FAKE_NAME),
        ]
        n_mock.return_value = copy.deepcopy(RECORD)
        self.cmd = network.ShowNetwork(self.app, self.namespace)

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)
        result = list(self.cmd.take_action(parsed_args))

        n_mock.assert_called_with('networks', FAKE_NAME)
        self.assertEqual(FILTERED, result)

    def test_show_all_options(self, n_mock):
        arglist = [FAKE_NAME]
        verifylist = [('identifier', FAKE_NAME)]
        n_mock.return_value = copy.deepcopy(RECORD)
        self.cmd = network.ShowNetwork(self.app, self.namespace)

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)
        result = list(self.cmd.take_action(parsed_args))

        n_mock.assert_called_with('networks', FAKE_NAME)
        self.assertEqual(FILTERED, result)
<commit_msg>Refactor TestShowNetwork: Use TestNetwork in TestShowNetwork<commit_after>#   Licensed under the Apache License, Version 2.0 (the "License"); you may
#   not use this file except in compliance with the License. You may obtain
#   a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#   WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#   License for the specific language governing permissions and limitations
#   under the License.
#

import copy
import mock

from openstackclient.common import exceptions
from openstackclient.network.v2 import network
from openstackclient.tests import fakes
from openstackclient.tests.identity.v2_0 import fakes as identity_fakes_v2
from openstackclient.tests.identity.v3 import fakes as identity_fakes_v3
from openstackclient.tests.network.v2 import fakes as network_fakes

RESOURCE = 'network'
RESOURCES = 'networks'
FAKE_ID = 'iditty'
FAKE_NAME = 'noo'
FAKE_PROJECT = 'yaa'
RECORD = {
    'id': FAKE_ID,
    'name': FAKE_NAME,
    'admin_state_up': True,
    'router:external': True,
    'status': 'ACTIVE',
    'subnets': ['a', 'b'],
    'tenant_id': FAKE_PROJECT,
}
RESPONSE = {RESOURCE: copy.deepcopy(RECORD)}
FILTERED = [
    (
        'id',
        'name',
        'project_id',
        'router_type',
        'state',
        'status',
        'subnets',
    ),
    (
        FAKE_ID,
        FAKE_NAME,
        FAKE_PROJECT,
        'External',
        'UP',
        'ACTIVE',
        'a, b',
    ),
]

class TestNetwork(network_fakes.TestNetworkV2):

    def setUp(self):
        super(TestNetwork, self).setUp()

        # Get a shortcut to the network client
        self.network = self.app.client_manager.network

        # Get a shortcut to the APIManager
        self.api = self.app.client_manager.network.api

class TestCreateNetworkIdentityV3(TestNetwork):

    def setUp(self):
        super(TestCreateNetworkIdentityV3, self).setUp()

        self.new_network = mock.Mock(return_value=copy.deepcopy(RESPONSE))
        self.network.create_network = self.new_network

        # Get the command object to test
        self.cmd = network.CreateNetwork(self.app, self.namespace)

        # Set identity client v3. And get a shortcut to Identity client.
        identity_client = identity_fakes_v3.FakeIdentityv3Client(
            endpoint=fakes.AUTH_URL,
            token=fakes.AUTH_TOKEN,
        )
        self.app.client_manager.identity = identity_client
        self.identity = self.app.client_manager.identity

        # Get a shortcut to the ProjectManager Mock
        self.projects_mock = self.identity.projects
        self.projects_mock.get.return_value = fakes.FakeResource(
            None,
            copy.deepcopy(identity_fakes_v3.PROJECT),
            loaded=True,
        )

        # Get a shortcut to the DomainManager Mock
        self.domains_mock = self.identity.domains
        self.domains_mock.get.return_value = fakes.FakeResource(
            None,
            copy.deepcopy(identity_fakes_v3.DOMAIN),
            loaded=True,
        )

    def test_create_no_options(self):
        arglist = [
            FAKE_NAME,
        ]
        verifylist = [
            ('name', FAKE_NAME),
            ('admin_state', True),
            ('shared', None),
            ('project', None),
        ]

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)
        result = list(self.cmd.take_action(parsed_args))

        self.network.create_network.assert_called_with({
            RESOURCE: {
                'admin_state_up': True,
                'name': FAKE_NAME,
            }
        })
        self.assertEqual(FILTERED, result)

    def test_create_all_options(self):
        arglist = [
            "--disable",
            "--share",
            "--project", identity_fakes_v3.project_name,
            "--project-domain", identity_fakes_v3.domain_name,
            FAKE_NAME,
        ]
        verifylist = [
            ('admin_state', False),
            ('shared', True),
            ('project', identity_fakes_v3.project_name),
            ('project_domain', identity_fakes_v3.domain_name),
            ('name', FAKE_NAME),
        ]

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)
        result = list(self.cmd.take_action(parsed_args))

        self.network.create_network.assert_called_with({
            RESOURCE: {
                'admin_state_up': False,
                'name': FAKE_NAME,
                'shared': True,
                'tenant_id': identity_fakes_v3.project_id,
            }
        })
        self.assertEqual(FILTERED, result)

    def test_create_other_options(self):
        arglist = [
            "--enable",
            "--no-share",
            FAKE_NAME,
        ]
        verifylist = [
            ('admin_state', True),
            ('shared', False),
            ('name', FAKE_NAME),
        ]

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)
        result = list(self.cmd.take_action(parsed_args))

        self.network.create_network.assert_called_with({
            RESOURCE: {
                'admin_state_up': True,
                'name': FAKE_NAME,
                'shared': False,
            }
        })
        self.assertEqual(FILTERED, result)

class TestCreateNetworkIdentityV2(TestNetwork):

    def setUp(self):
        super(TestCreateNetworkIdentityV2, self).setUp()

        self.new_network = mock.Mock(return_value=copy.deepcopy(RESPONSE))
        self.network.create_network = self.new_network

        # Get the command object to test
        self.cmd = network.CreateNetwork(self.app, self.namespace)

        # Set identity client v2. And get a shortcut to Identity client.
        identity_client = identity_fakes_v2.FakeIdentityv2Client(
            endpoint=fakes.AUTH_URL,
            token=fakes.AUTH_TOKEN,
        )
        self.app.client_manager.identity = identity_client
        self.identity = self.app.client_manager.identity

        # Get a shortcut to the ProjectManager Mock
        self.projects_mock = self.identity.tenants
        self.projects_mock.get.return_value = fakes.FakeResource(
            None,
            copy.deepcopy(identity_fakes_v2.PROJECT),
            loaded=True,
        )

        # There is no DomainManager Mock in fake identity v2.

    def test_create_with_project_identityv2(self):
        arglist = [
            "--project", identity_fakes_v2.project_name,
            FAKE_NAME,
        ]
        verifylist = [
            ('admin_state', True),
            ('shared', None),
            ('name', FAKE_NAME),
            ('project', identity_fakes_v2.project_name),
        ]

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)
        result = list(self.cmd.take_action(parsed_args))

        self.network.create_network.assert_called_with({
            RESOURCE: {
                'admin_state_up': True,
                'name': FAKE_NAME,
                'tenant_id': identity_fakes_v2.project_id,
            }
        })
        self.assertEqual(FILTERED, result)

    def test_create_with_domain_identityv2(self):
        arglist = [
            "--project", identity_fakes_v3.project_name,
            "--project-domain", identity_fakes_v3.domain_name,
            FAKE_NAME,
        ]
        verifylist = [
            ('admin_state', True),
            ('shared', None),
            ('project', identity_fakes_v3.project_name),
            ('project_domain', identity_fakes_v3.domain_name),
            ('name', FAKE_NAME),
        ]

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)

        self.assertRaises(
            AttributeError,
            self.cmd.take_action,
            parsed_args,
        )

class TestDeleteNetwork(TestNetwork):

    def setUp(self):
        super(TestDeleteNetwork, self).setUp()

        self.network.delete_network = mock.Mock(
            return_value=None
        )

        self.network.list_networks = mock.Mock(
            return_value={RESOURCES: [copy.deepcopy(RECORD)]}
        )

        # Get the command object to test
        self.cmd = network.DeleteNetwork(self.app, self.namespace)

    def test_delete(self):
        arglist = [
            FAKE_NAME,
        ]
        verifylist = [
            ('networks', [FAKE_NAME]),
        ]

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)
        result = self.cmd.take_action(parsed_args)

        self.network.delete_network.assert_called_with(FAKE_ID)
        self.assertEqual(None, result)

@mock.patch(
    'openstackclient.api.network_v2.APIv2.network_list'
)
class TestListNetwork(TestNetwork):

    columns = [
        'ID',
        'Name',
        'Subnets'
    ]
    columns_long = [
        'ID',
        'Name',
        'Status',
        'Project',
        'State',
        'Shared',
        'Subnets',
        'Network Type',
        'Router Type',
    ]

    data = [
        (FAKE_ID, FAKE_NAME, 'a, b'),
        (FAKE_ID, FAKE_NAME, 'a, b'),
    ]
    data_long = [
        (FAKE_ID, FAKE_NAME, 'ACTIVE', FAKE_PROJECT,
         'UP', '', 'a, b', '', 'External'),
        (FAKE_ID, FAKE_NAME, 'ACTIVE', FAKE_PROJECT,
         'UP', '', 'a, b', '', 'External'),
    ]

    def setUp(self):
        super(TestListNetwork, self).setUp()

        # Get the command object to test
        self.cmd = network.ListNetwork(self.app, self.namespace)

        self.NETWORK_LIST = [
            copy.deepcopy(RECORD),
            copy.deepcopy(RECORD),
        ]

    def test_network_list_no_options(self, network_list):
        network_list.return_value = self.NETWORK_LIST

        arglist = []
        verifylist = [
            ('external', False),
            ('long', False),
        ]
        parsed_args = self.check_parser(self.cmd, arglist, verifylist)

        # DisplayCommandBase.take_action() returns two tuples
        columns, data = self.cmd.take_action(parsed_args)

        # Set expected values
        network_list.assert_called_with(
            external=False,
        )

        self.assertEqual(tuple(self.columns), columns)
        self.assertEqual(self.data, list(data))

    def test_list_external(self, network_list):
        network_list.return_value = self.NETWORK_LIST

        arglist = [
            '--external',
        ]
        verifylist = [
            ('external', True),
            ('long', False),
        ]
        parsed_args = self.check_parser(self.cmd, arglist, verifylist)

        # DisplayCommandBase.take_action() returns two tuples
        columns, data = self.cmd.take_action(parsed_args)

        # Set expected values
        network_list.assert_called_with(
            external=True,
        )

        self.assertEqual(tuple(self.columns), columns)
        self.assertEqual(self.data, list(data))

    def test_network_list_long(self, network_list):
        network_list.return_value = self.NETWORK_LIST

        arglist = [
            '--long',
        ]
        verifylist = [
            ('long', True),
            ('external', False),
        ]
        parsed_args = self.check_parser(self.cmd, arglist, verifylist)

        # DisplayCommandBase.take_action() returns two tuples
        columns, data = self.cmd.take_action(parsed_args)

        # Set expected values
        network_list.assert_called_with(
            external=False,
        )

        self.assertEqual(columns, tuple(self.columns_long))
        self.assertEqual(self.data_long, list(data))

class TestSetNetwork(TestNetwork):

    def setUp(self):
        super(TestSetNetwork, self).setUp()

        self.network.update_network = mock.Mock(
            return_value=None
        )

        self.network.list_networks = mock.Mock(
            return_value={RESOURCES: [copy.deepcopy(RECORD)]}
        )

        # Get the command object to test
        self.cmd = network.SetNetwork(self.app, self.namespace)

    def test_set_this(self):
        arglist = [
            FAKE_NAME,
            '--enable',
            '--name', 'noob',
            '--share',
        ]
        verifylist = [
            ('identifier', FAKE_NAME),
            ('admin_state', True),
            ('name', 'noob'),
            ('shared', True),
        ]

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)
        result = self.cmd.take_action(parsed_args)

        exp = {'admin_state_up': True, 'name': 'noob', 'shared': True}
        exp_record = {RESOURCE: exp}
        self.network.update_network.assert_called_with(FAKE_ID, exp_record)
        self.assertEqual(None, result)

    def test_set_that(self):
        arglist = [
            FAKE_NAME,
            '--disable',
            '--no-share',
        ]
        verifylist = [
            ('identifier', FAKE_NAME),
            ('admin_state', False),
            ('shared', False),
        ]

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)
        result = self.cmd.take_action(parsed_args)

        exp = {'admin_state_up': False, 'shared': False}
        exp_record = {RESOURCE: exp}
        self.network.update_network.assert_called_with(FAKE_ID, exp_record)
        self.assertEqual(None, result)

    def test_set_nothing(self):
        arglist = [FAKE_NAME, ]
        verifylist = [('identifier', FAKE_NAME), ]

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)
        self.assertRaises(exceptions.CommandError, self.cmd.take_action,
                          parsed_args)

@mock.patch(
    'openstackclient.api.network_v2.APIv2.find_attr'
)
class TestShowNetwork(TestNetwork):

    def setUp(self):
        super(TestShowNetwork, self).setUp()

        # Get the command object to test
        self.cmd = network.ShowNetwork(self.app, self.namespace)

    def test_show_no_options(self, find_attr):
        arglist = [
            FAKE_NAME,
        ]
        verifylist = [
            ('identifier', FAKE_NAME),
        ]
        find_attr.return_value = copy.deepcopy(RECORD)

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)
        result = list(self.cmd.take_action(parsed_args))

        find_attr.assert_called_with('networks', FAKE_NAME)
        self.assertEqual(FILTERED, result)

    def test_show_all_options(self, find_attr):
        arglist = [FAKE_NAME]
        verifylist = [('identifier', FAKE_NAME)]
        find_attr.return_value = copy.deepcopy(RECORD)

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)
        result = list(self.cmd.take_action(parsed_args))

        find_attr.assert_called_with('networks', FAKE_NAME)
        self.assertEqual(FILTERED, result)
<|endoftext|>


<commit_before><commit_msg>[FIX] web: increase timeout<commit_after><|endoftext|>


<commit_before># Copyright Hybrid Logic Ltd.  See LICENSE file for details.
"""
Tests for :module:`admin.homebrew`.
"""

from twisted.python.filepath import FilePath
from twisted.trial.unittest import SynchronousTestCase
from twisted.python.usage import UsageError

from requests.exceptions import HTTPError

from admin.homebrew import (
    HomebrewOptions, get_checksum, get_dependency_graph, get_class_name,
)

class HomebrewOptionsTests(SynchronousTestCase):
    """
    Tests for :class:`HomebrewOptions`.
    """

    def test_flocker_version_required(self):
          """
          The ``--flocker-version`` option is not required.
          """
          options = HomebrewOptions()
          self.assertRaises(
              UsageError,
              options.parseOptions, ['--sdist', 'mysdist'])

    def test_sdist_required(self):
        """
        The ``--sdist`` option is not required.
        """
        options = HomebrewOptions()
        self.assertRaises(
            UsageError,
            options.parseOptions, ['--flocker-version', '0.3.0'])

    def test_output_file_required(self):
        """
        The ``--output-file`` option is required.
        """
        options = HomebrewOptions()
        self.assertRaises(
            UsageError,
            options.parseOptions,
            ['--flocker-version', '0.3.0',
             '--sdist', 'mysdist'])

# TODO make private methods private
# TODO release will have to use an sdist
# TODO update buildbot to call wrapper script
# TODO one function called by main which gets everything and returns a recipe
# this will help with faking

class GetChecksumTests(SynchronousTestCase):
    """
    Tests for X.
    """
    def test_checksum(self):
        """
        The sha1 hash of a file at a given URI is returned.
        """
        source_repo = FilePath(self.mktemp())
        source_repo.makedirs()
        file = source_repo.child('example_file')
        file.setContent("Some content")

        uri = 'file://' + file.path
        # TODO Make get_checksum take URI not URL
        self.assertEqual(
            '9f1a6ecf74e9f9b1ae52e8eb581d420e63e8453a',
            get_checksum(url=uri))

    def test_file_not_available(self):
        """
        If a requested file is not available in the repository, a 404 error is
        raised.
        """
        with self.assertRaises(HTTPError) as exception:
            get_checksum(url='file://' + FilePath(self.mktemp()).path)

        self.assertEqual(404, exception.exception.response.status_code)

class GetDependencyGraphTests(SynchronousTestCase):
    """
    Tests for X.
    """
    def test_get_dependency_graph(self):
        graph = get_dependency_graph(u'flocker')
        # We can be sure that flocker is installed if we are running this,
        # and pretty sure that setuptools is a dependency with no dependencies
        # of its own.
        # Perhaps a better test would installe a canned package.
        self.assertEqual(graph['setuptools'], {})

    def test_application_removed(self):
        """
        Applications cannot depend on themselves so they are not in the graph.
        """
        self.assertNotIn(u'flocker', get_dependency_graph(u'flocker'))

class GetClassNameTests(SynchronousTestCase):
    """
    Tests for X.
    """
    def test_disallowed_characters_removed(self):
        """
        Hyphens and periods are removed.
        """
        self.assertEqual(
            get_class_name(version='0.3.0-444-05215b'),
            'Flocker03044405215b'
        )

    def test_caps_after_disallowed(self):
        """
        If there is a letter following a disallowed character then it is
        capitalised.
        """
        self.assertEqual(
            get_class_name(version='0.3.0-444-g05215b'),
            'Flocker030444G05215b'
        )

    def test_disallowed_at_end(self):
        """
        If there is a letter following a disallowed character then it is
        capitalised.
        """
        self.assertEqual(
            get_class_name(version='0.3.0-444-g05215b-'),
            'Flocker030444G05215b'
        )

class GetFormattedDependencyListTests(SynchronousTestCase):
    """
    Tests for X.
    """
    # TODO this should return a list which is later formatted

class GetResourceStanzasTests(SynchronousTestCase):
    """
    Tests for X.
    """
    # TODO should return a dictionary of project names to URLs and Checksums
    # get_recipe should turn this dictionary into string
    def test_package_not_found(self):
        pass
<commit_msg>Test for formatting of resource stanzas<commit_after># Copyright Hybrid Logic Ltd.  See LICENSE file for details.
"""
Tests for :module:`admin.homebrew`.
"""

from twisted.python.filepath import FilePath
from twisted.trial.unittest import SynchronousTestCase
from twisted.python.usage import UsageError

from requests.exceptions import HTTPError

from admin.homebrew import (
    HomebrewOptions, get_checksum, get_dependency_graph, get_class_name,
    format_resource_stanzas,
)

class HomebrewOptionsTests(SynchronousTestCase):
    """
    Tests for :class:`HomebrewOptions`.
    """

    def test_flocker_version_required(self):
          """
          The ``--flocker-version`` option is not required.
          """
          options = HomebrewOptions()
          self.assertRaises(
              UsageError,
              options.parseOptions, ['--sdist', 'mysdist'])

    def test_sdist_required(self):
        """
        The ``--sdist`` option is not required.
        """
        options = HomebrewOptions()
        self.assertRaises(
            UsageError,
            options.parseOptions, ['--flocker-version', '0.3.0'])

    def test_output_file_required(self):
        """
        The ``--output-file`` option is required.
        """
        options = HomebrewOptions()
        self.assertRaises(
            UsageError,
            options.parseOptions,
            ['--flocker-version', '0.3.0',
             '--sdist', 'mysdist'])

# TODO make private methods private
# TODO release will have to use an sdist
# TODO update buildbot to call wrapper script
# TODO one function called by main which gets everything and returns a recipe
# this will help with faking

class GetChecksumTests(SynchronousTestCase):
    """
    Tests for X.
    """
    def test_checksum(self):
        """
        The sha1 hash of a file at a given URI is returned.
        """
        source_repo = FilePath(self.mktemp())
        source_repo.makedirs()
        file = source_repo.child('example_file')
        file.setContent("Some content")

        uri = 'file://' + file.path
        # TODO Make get_checksum take URI not URL
        self.assertEqual(
            '9f1a6ecf74e9f9b1ae52e8eb581d420e63e8453a',
            get_checksum(url=uri))

    def test_file_not_available(self):
        """
        If a requested file is not available in the repository, a 404 error is
        raised.
        """
        with self.assertRaises(HTTPError) as exception:
            get_checksum(url='file://' + FilePath(self.mktemp()).path)

        self.assertEqual(404, exception.exception.response.status_code)

class GetDependencyGraphTests(SynchronousTestCase):
    """
    Tests for X.
    """
    def test_get_dependency_graph(self):
        graph = get_dependency_graph(u'flocker')
        # We can be sure that flocker is installed if we are running this,
        # and pretty sure that setuptools is a dependency with no dependencies
        # of its own.
        # Perhaps a better test would installe a canned package.
        self.assertEqual(graph['setuptools'], {})

    def test_application_removed(self):
        """
        Applications cannot depend on themselves so they are not in the graph.
        """
        self.assertNotIn(u'flocker', get_dependency_graph(u'flocker'))

class GetClassNameTests(SynchronousTestCase):
    """
    Tests for X.
    """
    def test_disallowed_characters_removed(self):
        """
        Hyphens and periods are removed.
        """
        self.assertEqual(
            get_class_name(version='0.3.0-444-05215b'),
            'Flocker03044405215b'
        )

    def test_caps_after_disallowed(self):
        """
        If there is a letter following a disallowed character then it is
        capitalised.
        """
        self.assertEqual(
            get_class_name(version='0.3.0-444-g05215b'),
            'Flocker030444G05215b'
        )

    def test_disallowed_at_end(self):
        """
        If there is a letter following a disallowed character then it is
        capitalised.
        """
        self.assertEqual(
            get_class_name(version='0.3.0-444-g05215b-'),
            'Flocker030444G05215b'
        )

class FormatResourceStanzasTests(SynchronousTestCase):
    """
    Tests for X.
    """
    def test_two_resources(self):
        resources = [{
            "project_name": "six",
            "url": "https://example.com/six/six-1.9.0.tar.gz",
            "checksum": "d168e6d01f0900875c6ecebc97da72d0fda31129",
        },
        {
            "project_name": "treq",
            "url": "https://example.com/treq/treq-0.2.1.tar.gz",
            "checksum": "fc19b107d0cd6660f797ec6f82c3a61d5e2a768a",
        },
        ]
        expected = u"""
  resource "six" do
    url "https://example.com/six/six-1.9.0.tar.gz"
    sha1 "d168e6d01f0900875c6ecebc97da72d0fda31129"
  end

  resource "treq" do
    url "https://example.com/treq/treq-0.2.1.tar.gz"
    sha1 "fc19b107d0cd6660f797ec6f82c3a61d5e2a768a"
  end
"""
        self.assertEqual(expected, format_resource_stanzas(resources))

class GetFormattedDependencyListTests(SynchronousTestCase):
    """
    Tests for X.
    """
    # TODO this should return a list which is later formatted

class GetResourceStanzasTests(SynchronousTestCase):
    """
    Tests for X.
    """
    # TODO should return a dictionary of project names to URLs and Checksums
    # get_recipe should turn this dictionary into string
    def test_package_not_found(self):
        pass
<|endoftext|>