<commit_before>#!/usr/bin/python
#

# Copyright (C) 2010 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 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
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.


"""Script for unittesting the RAPI client module"""


import re
import unittest
import warnings

from ganeti import http
from ganeti import serializer

from ganeti.rapi import connector
from ganeti.rapi import rlib2
from ganeti.rapi import client

import testutils


_URI_RE = re.compile(r"https://(?P<host>.*):(?P<port>\d+)(?P<path>/.*)")


def _GetPathFromUri(uri):
  """Gets the path and query from a URI.

  """
  match = _URI_RE.match(uri)
  if match:
    return match.groupdict()["path"]
  else:
    return None


class HttpResponseMock:
  """Dumb mock of httplib.HTTPResponse.

  """

  def __init__(self, code, data):
    self.code = code
    self._data = data

  def read(self):
    return self._data


class OpenerDirectorMock:
  """Mock for urllib.OpenerDirector.

  """

  def __init__(self, rapi):
    self._rapi = rapi
    self.last_request = None

  def open(self, req):
    self.last_request = req

    path = _GetPathFromUri(req.get_full_url())
    code, resp_body = self._rapi.FetchResponse(path, req.get_method())
    return HttpResponseMock(code, resp_body)


class RapiMock(object):

  def __init__(self):
    self._mapper = connector.Mapper()
    self._responses = []
    self._last_handler = None

  def AddResponse(self, response):
    self._responses.insert(0, response)

  def PopResponse(self):
    if len(self._responses) > 0:
      return self._responses.pop()
    else:
      return None

  def GetLastHandler(self):
    return self._last_handler

  def FetchResponse(self, path, method):
    code = 200
    response = None

    try:
      HandlerClass, items, args = self._mapper.getController(path)
      self._last_handler = HandlerClass(items, args, None)
      if not hasattr(self._last_handler, method.upper()):
        code = 501
        response = "Method not implemented"
    except http.HttpException, ex:
      code = ex.code
      response = ex.message

    if not response:
      response = self.PopResponse()

    return code, response


class RapiMockTest(unittest.TestCase):
  def test(self):
    rapi = RapiMock()
    path = "/version"
    self.assertEqual((404, None), rapi.FetchResponse("/foo", "GET"))
    self.assertEqual((501, "Method not implemented"),
                     rapi.FetchResponse("/version", "POST"))
    rapi.AddResponse("2")
    code, response = rapi.FetchResponse("/version", "GET")
    self.assertEqual(200, code)
    self.assertEqual("2", response)
    self.failUnless(isinstance(rapi.GetLastHandler(), rlib2.R_version))


class GanetiRapiClientTests(testutils.GanetiTestCase):
  def setUp(self):
    testutils.GanetiTestCase.setUp(self)

    self.rapi = RapiMock()
    self.http = OpenerDirectorMock(self.rapi)
    self.client = client.GanetiRapiClient('master.foo.com')
    self.client._http = self.http<commit_msg>Support different HTTP error codes in RAPI client unittest mock<commit_after>#!/usr/bin/python
#

# Copyright (C) 2010 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 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
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.


"""Script for unittesting the RAPI client module"""


import re
import unittest
import warnings

from ganeti import http
from ganeti import serializer

from ganeti.rapi import connector
from ganeti.rapi import rlib2
from ganeti.rapi import client

import testutils


_URI_RE = re.compile(r"https://(?P<host>.*):(?P<port>\d+)(?P<path>/.*)")


def _GetPathFromUri(uri):
  """Gets the path and query from a URI.

  """
  match = _URI_RE.match(uri)
  if match:
    return match.groupdict()["path"]
  else:
    return None


class HttpResponseMock:
  """Dumb mock of httplib.HTTPResponse.

  """

  def __init__(self, code, data):
    self.code = code
    self._data = data

  def read(self):
    return self._data


class OpenerDirectorMock:
  """Mock for urllib.OpenerDirector.

  """

  def __init__(self, rapi):
    self._rapi = rapi
    self.last_request = None

  def open(self, req):
    self.last_request = req

    path = _GetPathFromUri(req.get_full_url())
    code, resp_body = self._rapi.FetchResponse(path, req.get_method())
    return HttpResponseMock(code, resp_body)


class RapiMock(object):
  def __init__(self):
    self._mapper = connector.Mapper()
    self._responses = []
    self._last_handler = None

  def AddResponse(self, response, code=200):
    self._responses.insert(0, (code, response))

  def GetLastHandler(self):
    return self._last_handler

  def FetchResponse(self, path, method):
    try:
      HandlerClass, items, args = self._mapper.getController(path)
      self._last_handler = HandlerClass(items, args, None)
      if not hasattr(self._last_handler, method.upper()):
        raise http.HttpNotImplemented(message="Method not implemented")

    except http.HttpException, ex:
      code = ex.code
      response = ex.message
    else:
      if not self._responses:
        raise Exception("No responses")

      (code, response) = self._responses.pop()

    return code, response


class RapiMockTest(unittest.TestCase):
  def test(self):
    rapi = RapiMock()
    path = "/version"
    self.assertEqual((404, None), rapi.FetchResponse("/foo", "GET"))
    self.assertEqual((501, "Method not implemented"),
                     rapi.FetchResponse("/version", "POST"))
    rapi.AddResponse("2")
    code, response = rapi.FetchResponse("/version", "GET")
    self.assertEqual(200, code)
    self.assertEqual("2", response)
    self.failUnless(isinstance(rapi.GetLastHandler(), rlib2.R_version))


class GanetiRapiClientTests(testutils.GanetiTestCase):
  def setUp(self):
    testutils.GanetiTestCase.setUp(self)

    self.rapi = RapiMock()
    self.http = OpenerDirectorMock(self.rapi)
    self.client = client.GanetiRapiClient('master.foo.com')
    self.client._http = self.http
{'fraction_non_alphanumeric': 0.1080701754385965, 'fraction_numerical': 0.009824561403508772, 'mean_word_length': 3.6393229166666665, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 10, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4023403', 'n_tokens_mistral': 2278, 'n_tokens_neox': 2152, 'n_words': 661}