class TestApi(unittest.TestCase):
    """ Test the api module. """

    def setUp(self):
        client = config.unittest_client()
        self.api = Api(client["apid_uri"], {"client_id": client["client_id"], "client_secret": client["client_secret"]})
        self.client = client

    def test_api_encode(self):
        # Python natives should be encoded into JSON
        self.assertEqual(api_encode(True), "true")
        self.assertEqual(api_encode(False), "false")
        json.loads(api_encode(["foo", "bar"]))
        json.loads(api_encode({"foo": True, "bar": None}))

    def test_api_object(self):
        # should prepend https:// if protocol is missing
        api = Api("foo.janrain.com")
        self.assertEqual(api.api_url, "https://foo.janrain.com")

        # responses should have stat
        result = self.api.call("entity.count", type_name="user")
        self.assertTrue("stat" in result)

        # oauth/token returns 400 or 401 which should *not* be a URLError
        with self.assertRaises(ApiResponseError):
            self.api.call("/oauth/token")
    def test_user_agent(self):
        # default user agent string will be used if not defined when object is
        # instantiated
        api1 = Api("foo.janrain.com")
        self.assertIsNotNone(api1.user_agent)

        api2 = Api("foo.janrain.com", user_agent="foobar")
        self.assertEqual(api2.user_agent, "foobar")
Example #3
0
    def setUp(self):
        try:
            client = config.get_client('janrain-capture-api-unittest')
            apid_uri = client['apid_uri']
            client_id = client['client_id']
            client_secret = client['client_secret']
        except:
            apid_uri = environ['APID_URI']
            client_id = environ['CLIENT_ID']
            client_secret = environ['CLIENT_SECRET']

        self.api = Api(apid_uri, {
            'client_id': client_id,
            'client_secret': client_secret,
        })
    def test_request_timeout(self):
        # The request_timeout should be passed to requests.post
        response = requests.Response()
        response.status_code = 200
        response._content = b'{"stat": "ok"}'

        api = Api("foo.janrain.com", {
            'client_id': 123,
            'client_secret': '456'
        },
                  request_timeout=5)

        with mock.patch('janrain.capture.api.requests.post',
                        return_value=response) as mock_post:
            api.call("clients/list", has_features=["owner"])
            self.assertEqual(mock_post.call_args[1]['timeout'], 5)
Example #5
0
 def setUp(self):
     client = config.unittest_client()
     self.api = Api(client['apid_uri'], {
         'client_id': client['client_id'],
         'client_secret': client['client_secret']
     })
     self.client = client
Example #6
0
class TestApi(unittest.TestCase):
    """ Test the api module. """
    def setUp(self):
        try:
            client = config.get_client('janrain-capture-api-unittest')
            apid_uri = client['apid_uri']
            client_id = client['client_id']
            client_secret = client['client_secret']
        except:
            apid_uri = environ['APID_URI']
            client_id = environ['CLIENT_ID']
            client_secret = environ['CLIENT_SECRET']

        self.api = Api(apid_uri, {
            'client_id': client_id,
            'client_secret': client_secret,
        })

    def test_api_encode(self):
        # Python natives should be encoded into JSON
        self.assertEqual(api_encode(True), b"true")
        self.assertEqual(api_encode(False), b"false")
        json.loads(api_encode(['foo', 'bar']).decode('utf-8'))
        json.loads(api_encode({'foo': True, 'bar': None}).decode('utf-8'))

    def test_api_object(self):
        # should prepend https:// if protocol is missing
        api = Api("foo.janrain.com")
        self.assertEqual(api.api_url, "https://foo.janrain.com")

        # responses should have stat
        result = self.api.call("clients/list", has_features=["owner"])
        self.assertTrue("stat" in result)

        # oauth/token returns 400 or 401 which should *not* be a HTTPError
        with self.assertRaises(ApiResponseError):
            self.api.call("/oauth/token")

    def test_user_agent(self):
        # default user agent string will be used if not defined when object is
        # instantiated
        api1 = Api("foo.janrain.com")
        self.assertIsNotNone(api1.user_agent)

        api2 = Api("foo.janrain.com", user_agent="foobar")
        self.assertEqual(api2.user_agent, "foobar")
Example #7
0
class TestApi(unittest.TestCase):
    """ Test the api module. """
    def setUp(self):
        try:
            client = config.get_client('janrain-capture-api-unittest')
            apid_uri = client['apid_uri']
            client_id = client['client_id']
            client_secret = client['client_secret']
        except:
            apid_uri = environ['APID_URI']
            client_id = environ['CLIENT_ID']
            client_secret = environ['CLIENT_SECRET']

        self.api = Api(apid_uri, {
            'client_id': client_id,
            'client_secret': client_secret,
        })

    def test_api_encode(self):
        # Python natives should be encoded into JSON
        self.assertEqual(api_encode(True), b"true")
        self.assertEqual(api_encode(False), b"false")
        json.loads(api_encode(['foo', 'bar']).decode('utf-8'))
        json.loads(api_encode({'foo': True, 'bar': None}).decode('utf-8'))

    def test_api_object(self):
        # should prepend https:// if protocol is missing
        api = Api("foo.janrain.com")
        self.assertEqual(api.api_url, "https://foo.janrain.com")

        # responses should have stat
        result = self.api.call("clients/list", has_features=["owner"])
        self.assertTrue("stat" in result)

        # oauth/token returns 400 or 401 which should *not* be a HTTPError
        with self.assertRaises(ApiResponseError):
            self.api.call("/oauth/token")

    def test_user_agent(self):
        # default user agent string will be used if not defined when object is
        # instantiated
        api1 = Api("foo.janrain.com")
        self.assertIsNotNone(api1.user_agent)

        api2 = Api("foo.janrain.com", user_agent="foobar")
        self.assertEqual(api2.user_agent, "foobar")
    def test_api_object(self):
        # should prepend https:// if protocol is missing
        api = Api("foo.janrain.com")
        self.assertEqual(api.api_url, "https://foo.janrain.com")

        # responses should have stat
        result = self.api.call("clients/list", has_features=["owner"])
        self.assertTrue("stat" in result)

        # oauth/token returns 400 or 401 which should *not* be a HTTPError
        with self.assertRaises(ApiResponseError):
            self.api.call("/oauth/token")
Example #9
0
class TestErrors(unittest.TestCase):
    def setUp(self):
        try:
            client = config.get_client('janrain-capture-api-unittest')
            apid_uri = client['apid_uri']
            client_id = client['client_id']
            client_secret = client['client_secret']
        except:
            apid_uri = environ['APID_URI']
            client_id = environ['CLIENT_ID']
            client_secret = environ['CLIENT_SECRET']

        self.api = Api(apid_uri, {
            'client_id': client_id,
            'client_secret': client_secret,
        })

    def test_api_response_error(self):
        with self.assertRaises(HTTPError):
            self.api.call('/foobar')

        with self.assertRaises(ApiResponseError):
            self.api.call('/entity')

        # HTTP errors come from requests library
        self.api.api_url = self.api.api_url.replace('https:', 'http:')
        with self.assertRaises(HTTPError):
            self.api.call('/entity')
        self.api.api_url = self.api.api_url.replace('http:', 'https:')
Example #10
0
def update_capture_user(sender, **kwargs):
    # Not necessary to update Capture on create since Capture provides the data
    # initially in the authentication backend.
    if not kwargs['created']:
        user = kwargs['instance']
        try:
            capture_user = CaptureUser.objects.get(user=user)
        except CaptureUser.DoesNotExist:
            return

        attribute_map = get_attribute_map()
        attributes = {}

        for user_attr, entity_attr in attribute_map.items():
            attributes[entity_attr] = getattr(user, user_attr)

        # Use client_id and client_secret since this update may be initiated by
        # a Django administrator.
        api = Api(settings.JANRAIN_CAPTURE['server'])
        response = api.call("/entity.update", type_name=get_entity_type(),
                            uuid=capture_user.uuid,
                            client_id=settings.JANRAIN_CAPTURE['client_id'],
                            client_secret=settings.JANRAIN_CAPTURE['client_secret'],
                            value=attributes)
Example #11
0
class TestErrors(unittest.TestCase):
    def setUp(self):
        client = config.unittest_client()
        self.api = Api(client['apid_uri'], {
            'client_id': client['client_id'],
            'client_secret': client['client_secret']
        })
                           
    def test_invalid_api_call_error(self):
        with self.assertRaises(InvalidApiCallError):
            self.api.call('/foobar')
    
    def test_invalid_url_error(self):
        with self.assertRaises(JanrainInvalidUrlError):
            orig_url = self.api.api_url
            self.api.api_url = "https://foobar.janraincapture.com"
            self.api.call("/entity")
            self.api.api_url = orig_url
            
    def test_api_response_error(self):
        with self.assertRaises(ApiResponseError):
            self.api.call('/entity')
#targetSecret = ''
#mymod = 100000
########

timestr = time.strftime("%Y%m%d-%H%M%S")
with open("res//results-" + target + "-" + typeName + "-" + timestr + ".csv",
          "x",
          newline='') as csv_file:
    writer = csv.writer(csv_file)

    #    creds = config.client(target)

    #   api = Api(creds['apid_uri'], creds)
    defaults = {'client_id': targetID, 'client_secret': targetSecret}

    api = Api(targetUrl, defaults)

    result = api.call('/entity.count', type_name=typeName)
    print("/entity.count == ", result)

    mycount = 0
    last_id = 0
    z = []
    while True:
        #        if(mycount % mymod == 0):
        print("mycount = ", mycount)
        try:
            response = api.call(
                '/entity.find',
                type_name=typeName,
                max_results=10000,
Example #13
0
    def init_api(self, api_class=None):
        """
        Initialize a janrain.capture.Api() instance for the credentials that
        were specified on the command line or environment variables. This
        method will use the first credentials it finds, looking in the
        following order:

        1. A client_id and client_secret specified on the command line
        2. A configuration key specified on the command line
        3. The default client as specified with a flag on the command line
        4. The CAPTURE_CLIENT_ID and CAPTURE_CLIENT_SECRET environment vars

        Returns:
            A janrain.capture.Api instance

        """
        if not self._parsed_args:
            raise Exception("You must call the parse_args() method before " \
                            "the init_api() method.")

        args = self._parsed_args

        if args.client_id and args.client_secret:
            credentials = {
                'client_id': args.client_id,
                'client_secret': args.client_secret
            }

        elif args.config_key:
            credentials = config.get_settings(args.config_key)

        elif args.default_client:
            credentials = config.default_client()

        elif 'CAPTURE_CLIENT_ID' in os.environ \
            and 'CAPTURE_CLIENT_SECRET' in os.environ:
            credentials = {
                'client_id': os.environ['CAPTURE_CLIENT_ID'],
                'client_secret': os.environ['CAPTURE_CLIENT_SECRET']
            }

        else:
            message = "You did not specify credentials to authenticate " \
                      "with the Capture API."
            raise JanrainCredentialsError(message)

        if args.apid_uri:
            credentials['apid_uri'] = args.apid_uri

        elif 'apid_uri' not in credentials:
            if 'CAPTURE_APID_URI' in os.environ:
                credentials['apid_uri'] = os.environ['CAPTURE_APID_URI']
            else:
                message = "You did not specify the URL to the Capture API"
                raise JanrainCredentialsError(message)

        defaults = {k: credentials[k] for k in ('client_id', 'client_secret')}

        if api_class:
            return api_class(credentials['apid_uri'], defaults)
        else:
            return Api(credentials['apid_uri'], defaults)
Example #14
0
 def setUp(self):
     client = config.unittest_client()
     self.api = Api(client["apid_uri"], {"client_id": client["client_id"], "client_secret": client["client_secret"]})
     self.client = client
## ch4-int deets
typeName = "user"
target = 'ch4-stage'
#mymod = 100000
########

timestr = time.strftime("%Y%m%d-%H%M%S")
with open("results-" + target + "-" + typeName + "-" + timestr + ".csv",
          "x",
          newline='') as csv_file:
    writer = csv.writer(csv_file)

    creds = config.client(target)

    api = Api(creds['apid_uri'], creds)

    result = api.call('/entity.count', type_name=typeName)
    print(result)

    mycount = 0
    last_id = 0
    while True:
        #        if(mycount % mymod == 0):
        print(mycount)
        try:
            response = api.call(
                '/entity.find',
                type_name=typeName,
                max_results=10000,
                attributes='["id", "uuid", "email", "lastUpdated"]',