Пример #1
0
 def test_connect(self, mock_HTTPSConnection):
     _imgur = CLIImgur()
     _imgur.connect()
     mock_HTTPSConnection.assert_has_calls(
         [
             call('api.imgur.com')
         ]
     )
Пример #2
0
 def setup(self):
     self.imgur = CLIImgur()
     self.imgur.connect()
     self._enter_token_msg = self.imgur._enter_token_msg
     self._auth_url = self.imgur._auth_url
     self._auth_msg = self.imgur._auth_msg
     self._no_album_msg = self.imgur._no_album_msg
     self._token_config = (
         '[Token]\n'
         'access_token = 0000000000000000000000000000000000000000\n'
         'refresh_token = 1111111111111111111111111111111111111111\n'
     )
     self._token_response = (
         '{"access_token":"2222222222222222222222222222222222222222",'
         '"expires_in":3600,'
         '"token_type":"bearer",'
         '"scope":null,'
         '"refresh_token":"3333333333333333333333333333333333333333",'
         '"account_username":"******"}'
     )
     self._token_json_response = {
         u'access_token': u'2222222222222222222222222222222222222222',
         u'expires_in': 3600,
         u'token_type': u'bearer',
         u'account_username': u'carlcarl',
         u'scope': None,
         u'refresh_token': u'3333333333333333333333333333333333333333'
     }
     self._album_response = (
         '{"data":[{"id":"XXXXX",'
         '"title":"temp",'
         '"description":null,'
         '"datetime":1352238500,'
         '"cover":"Oin6z",'
         '"cover_width":1891,'
         '"cover_height":967,'
         '"account_url":"carlcarl",'
         '"privacy":"hidden",'
         '"layout":"grid",'
         '"views":2,'
         '"link":"http:\/\/imgur.com\/a\/XXXXX",'
         '"favorite":false,'
         '"nsfw":null,'
         '"section":null,'
         '"deletehash":"000000000000000",'
         '"order":0}],'
         '"success":true,'
         '"status":200}'
     )
     self._album_fail_response = (
         '{"data":{"error": "fail"},'
         '"success":false,'
         '"status":200}'
     )
     self._album_json_response = {
         u'status': 200,
         u'data': [
             {
                 u'deletehash': u'000000000000000',
                 u'layout': u'grid',
                 u'description': None,
                 u'title': u'temp',
                 u'cover_height': 967,
                 u'views': 2,
                 u'privacy': u'hidden',
                 u'cover': u'Oin6z',
                 u'datetime': 1352238500,
                 u'account_url': u'carlcarl',
                 u'favorite': False,
                 u'cover_width': 1891,
                 u'link': u'http://imgur.com/a/XXXXX',
                 u'section': None,
                 u'nsfw': None,
                 u'order': 0,
                 u'id': u'XXXXX'
             }
         ],
         u'success': True
     }
     self._albums = [
         {
             'id': '1',
             'title': 'hello',
             'privacy': 'public'
         },
         {
             'id': '2',
             'title': 'hello2',
             'privacy': 'private'
         }
     ]
     self._image_link = 'http://i.imgur.com/xxxxxxx.jpg'
     self._delete_hash = 'xxxxxxxxxxxxxxx'
Пример #3
0
class TestCLIImgur:

    def setup(self):
        self.imgur = CLIImgur()
        self.imgur.connect()
        self._enter_token_msg = self.imgur._enter_token_msg
        self._auth_url = self.imgur._auth_url
        self._auth_msg = self.imgur._auth_msg
        self._no_album_msg = self.imgur._no_album_msg
        self._token_config = (
            '[Token]\n'
            'access_token = 0000000000000000000000000000000000000000\n'
            'refresh_token = 1111111111111111111111111111111111111111\n'
        )
        self._token_response = (
            '{"access_token":"2222222222222222222222222222222222222222",'
            '"expires_in":3600,'
            '"token_type":"bearer",'
            '"scope":null,'
            '"refresh_token":"3333333333333333333333333333333333333333",'
            '"account_username":"******"}'
        )
        self._token_json_response = {
            u'access_token': u'2222222222222222222222222222222222222222',
            u'expires_in': 3600,
            u'token_type': u'bearer',
            u'account_username': u'carlcarl',
            u'scope': None,
            u'refresh_token': u'3333333333333333333333333333333333333333'
        }
        self._album_response = (
            '{"data":[{"id":"XXXXX",'
            '"title":"temp",'
            '"description":null,'
            '"datetime":1352238500,'
            '"cover":"Oin6z",'
            '"cover_width":1891,'
            '"cover_height":967,'
            '"account_url":"carlcarl",'
            '"privacy":"hidden",'
            '"layout":"grid",'
            '"views":2,'
            '"link":"http:\/\/imgur.com\/a\/XXXXX",'
            '"favorite":false,'
            '"nsfw":null,'
            '"section":null,'
            '"deletehash":"000000000000000",'
            '"order":0}],'
            '"success":true,'
            '"status":200}'
        )
        self._album_fail_response = (
            '{"data":{"error": "fail"},'
            '"success":false,'
            '"status":200}'
        )
        self._album_json_response = {
            u'status': 200,
            u'data': [
                {
                    u'deletehash': u'000000000000000',
                    u'layout': u'grid',
                    u'description': None,
                    u'title': u'temp',
                    u'cover_height': 967,
                    u'views': 2,
                    u'privacy': u'hidden',
                    u'cover': u'Oin6z',
                    u'datetime': 1352238500,
                    u'account_url': u'carlcarl',
                    u'favorite': False,
                    u'cover_width': 1891,
                    u'link': u'http://imgur.com/a/XXXXX',
                    u'section': None,
                    u'nsfw': None,
                    u'order': 0,
                    u'id': u'XXXXX'
                }
            ],
            u'success': True
        }
        self._albums = [
            {
                'id': '1',
                'title': 'hello',
                'privacy': 'public'
            },
            {
                'id': '2',
                'title': 'hello2',
                'privacy': 'private'
            }
        ]
        self._image_link = 'http://i.imgur.com/xxxxxxx.jpg'
        self._delete_hash = 'xxxxxxxxxxxxxxx'

    @pytest.fixture(scope='function')
    def mock_HTTPSConnection(self, request):
        m = mock.patch('imgurup.httplib.HTTPSConnection')
        ret = m.start()
        request.addfinalizer(m.stop)
        return ret

    def test_connect(self, mock_HTTPSConnection):
        _imgur = CLIImgur()
        _imgur.connect()
        mock_HTTPSConnection.assert_has_calls(
            [
                call('api.imgur.com')
            ]
        )

    def test_set_tokens_using_config(self, monkeypatch):

        with patch(get_builtin_name('open'), return_value=io.StringIO(self._token_config)):
            self.imgur.set_tokens_using_config()
            assert self.imgur._access_token == '0000000000000000000000000000000000000000'
            assert self.imgur._refresh_token == '1111111111111111111111111111111111111111'

    def test_is_success(self):
        response = {}
        response['success'] = True
        response['data'] = {}
        response['data']['error'] = 'error'
        assert self.imgur.is_success(response) is True
        response['success'] = False
        assert self.imgur.is_success(response) is False

    def test_write_tokens_to_config(self):
        from mock import mock_open
        self.imgur._access_token = '0000000000000000000000000000000000000000'
        self.imgur._refresh_token = '1111111111111111111111111111111111111111'
        with patch('imgurup.SafeConfigParser.read'):
            m = mock_open()
            with patch(get_builtin_name('open'), m, create=True):
                self.imgur.write_tokens_to_config()
                m.assert_called_once_with(self.imgur.CONFIG_PATH, 'w')
                handle = m()
                handle.write.assert_has_calls(
                    [
                        call('[Token]\n'),
                        call('access_token = 0000000000000000000000000000000000000000\n'),
                        call('refresh_token = 1111111111111111111111111111111111111111\n'),
                    ]
                )

    def test_get_error_dialog_args(self):
        assert self.imgur.get_error_dialog_args() is None

    def test_get_auth_msg_dialog_args(self):
        with pytest.raises(NotImplementedError):
            self.imgur.get_auth_msg_dialog_args(self._auth_msg, self._auth_url)

    def test_get_enter_pin_dialog_args(self):
        with pytest.raises(NotImplementedError):
            self.imgur.get_enter_pin_dialog_args(self._enter_token_msg)

    @pytest.mark.httpretty
    def test_request_album_list_me_success(self, monkeypatch):
        httpretty.register_uri(
            httpretty.GET,
            "https://api.imgur.com/3/account/me/albums",
            body=self._album_response,
            status=200
        )
        with patch(get_builtin_name('open'), return_value=io.StringIO(self._token_config)):
            json_response = self.imgur.request_album_list()
            assert len(json_response) == 1

    @pytest.mark.httpretty
    def test_request_album_list_carlcarl_success(self, monkeypatch):
        httpretty.register_uri(
            httpretty.GET,
            "https://api.imgur.com/3/account/carlcarl/albums",
            body=self._album_response,
            status=200
        )
        with patch(get_builtin_name('open'), return_value=io.StringIO(self._token_config)):
            json_response = self.imgur.request_album_list(account='carlcarl')
            assert len(json_response) == 1

    @pytest.mark.httpretty
    def test_request_album_list_me_fail(self, monkeypatch):
        httpretty.register_uri(
            httpretty.GET,
            "https://api.imgur.com/3/account/me/albums",
            body=self._album_fail_response,
            status=200
        )
        m = mock.Mock(return_value=None)
        monkeypatch.setattr(
            imgurup.CLIImgur,
            'request_new_tokens_and_update',
            m
        )
        monkeypatch.setattr(
            imgurup.CLIImgur,
            'write_tokens_to_config',
            m
        )
        monkeypatch.setattr(
            imgurup.time,
            'sleep',
            m
        )
        with pytest.raises(SystemExit):
            self.imgur.request_album_list()

    @pytest.mark.httpretty
    def test_request_new_token(self):
        httpretty.register_uri(
            httpretty.POST,
            "https://api.imgur.com/oauth2/token",
            body=self._token_response,
            status=200
        )
        json_response = self.imgur.request_new_tokens()
        assert json_response == self._token_json_response

    @pytest.mark.httpretty
    def test_request_new_tokens_and_update(self):
        httpretty.register_uri(
            httpretty.POST,
            "https://api.imgur.com/oauth2/token",
            body=self._token_response,
            status=200
        )
        # Fail case which without token values in config
        with patch(get_builtin_name('open'), return_value=io.StringIO('')):
            with pytest.raises(SystemExit):
                self.imgur.request_new_tokens_and_update()

        # Success case
        with patch(get_builtin_name('open'), return_value=io.StringIO(self._token_config)):
            self.imgur.request_new_tokens_and_update()
            assert self.imgur._access_token == '2222222222222222222222222222222222222222'
            assert self.imgur._refresh_token == '3333333333333333333333333333333333333333'

        self.imgur._refresh_token = '3333333333333333333333333333333333333333'
        with patch('imgurup.CLIImgur.request_new_tokens') as request_new_tokens:
            request_new_tokens.return_value = {
                'success': False,
                'data': {
                    'error': 'error'
                }
            }
            with pytest.raises(SystemExit):
                self.imgur.request_new_tokens_and_update()

    @pytest.fixture(scope='function')
    def mock_raw_input(self, request):
        m = mock.patch('imgurup.input')
        ret = m.start()
        request.addfinalizer(m.stop)
        return ret

    def test_ask_pin(self, mock_raw_input):
        pin = '000000'
        mock_raw_input.return_value = pin
        assert self.imgur.ask_pin(
            self._auth_msg,
            self._auth_url,
            self._enter_token_msg) == pin

    @pytest.fixture(scope='function')
    def mock_ask_pin(self, request):
        m = mock.patch('imgurup.CLIImgur.ask_pin')
        ret = m.start()
        request.addfinalizer(m.stop)
        return ret

    @pytest.mark.httpretty
    def test_auth(self, mock_ask_pin):
        mock_ask_pin.return_value = '000000'
        httpretty.register_uri(
            httpretty.POST,
            'https://api.imgur.com/oauth2/token',
            body=(
                '{"success":false,'
                '"data":{"error":"error"} }'
            ),
            status=200
        )
        with pytest.raises(SystemExit):
            self.imgur.auth()

        httpretty.register_uri(
            httpretty.POST,
            'https://api.imgur.com/oauth2/token',
            body=(
                '{"success":true,'
                '"access_token":"1111111111111111111111111111111111111111",'
                '"refresh_token":"2222222222222222222222222222222222222222"}'
            ),
            status=200
        )
        self.imgur.auth()
        assert self.imgur._access_token == '1111111111111111111111111111111111111111'
        assert self.imgur._refresh_token == '2222222222222222222222222222222222222222'

    def test_get_ask_image_path_dialog_args(self):
        with pytest.raises(NotImplementedError):
            self.imgur.get_ask_image_path_dialog_args()

    def test_ask_image_path(self, mock_raw_input):
        path = '/home/test/test.jpg'
        mock_raw_input.return_value = path
        assert self.imgur.ask_image_path() == path

    def test_get_ask_album_id_dialog_args(self):
        with pytest.raises(NotImplementedError):
            self.imgur.get_ask_album_id_dialog_args(
                self._albums,
                self._no_album_msg
            )

    def test_ask_album_id(self):
        with patch('imgurup.input', return_value=1):
            assert self.imgur.ask_album_id(self._albums) == '1'

    def test_get_show_link_dialog_args(self):
        with pytest.raises(NotImplementedError):
            self.imgur.get_show_link_dialog_args({})

    @pytest.fixture(scope='function')
    def mock_print(self, request):
        m = mock.patch(get_builtin_name('print'))
        ret = m.start()
        request.addfinalizer(m.stop)
        return ret

    def test_show_link(self, mock_print):
        self.imgur.show_link(self._image_link, self._delete_hash)
        mock_print.assert_has_calls(
            [
                call('Link: http://i.imgur.com/xxxxxxx.jpg'),
                call('Delete link: http://imgur.com/delete/xxxxxxxxxxxxxxx')
            ]
        )

    def test_encode_multipart_data(self):
        """Just test if the function can work"""
        post_data = {
            'title': 'test',
        }
        files = {
            'image': os.path.join(
                os.path.dirname(os.path.realpath(__file__)),
                'images',
                'test.jpg'
            ),
        }
        try:
            self.imgur._encode_multipart_data(post_data, files)
            assert True
        except:
            assert False


    @pytest.mark.httpretty
    def test_request_upload_image_success(self):
        httpretty.register_uri(
            httpretty.POST,
            'https://api.imgur.com/3/image',
            body=self._album_response,
            status=200
        )
        json_response = self.imgur.request_upload_image(
            'https://api.imgur.com/3/image',
            body='',
            headers={}
        )
        assert len(json_response) == 1

    @pytest.mark.httpretty
    def test_request_upload_image_fail(self, monkeypatch):
        httpretty.register_uri(
            httpretty.POST,
            'https://api.imgur.com/3/image',
            body=self._album_fail_response,
            status=200
        )
        m = mock.Mock(return_value=None)
        monkeypatch.setattr(
            imgurup.CLIImgur,
            'request_new_tokens_and_update',
            m
        )
        monkeypatch.setattr(
            imgurup.CLIImgur,
            'write_tokens_to_config',
            m
        )
        monkeypatch.setattr(
            imgurup.time,
            'sleep',
            m
        )
        with pytest.raises(SystemExit):
            self.imgur.request_upload_image(
                'https://api.imgur.com/3/image',
                body='',
                headers={}
            )