Exemplo n.º 1
0
    def test_flip_color(self):
        """Flip colour"""
        self.assertEqual(AlfredBundler.flip_color('000000'), 'ffffff')
        self.assertEqual(AlfredBundler.flip_color('ffffff'), '000000')

        self.assertEqual(AlfredBundler.flip_color('000000'), 'ffffff')
        self.assertEqual(AlfredBundler.flip_color('ffffff'), '000000')
Exemplo n.º 2
0
 def test_bundle_id(self):
     """Bundle ID"""
     bid = AlfredBundler._bundle_id()
     self.assertEqual(bid, 'net.deanishe.alfred-bundler-python-test')
     # Call again to test against cached value
     self.assertEqual(AlfredBundler._bundle_id(),
                      'net.deanishe.alfred-bundler-python-test')
Exemplo n.º 3
0
    def test_init(self):
        """Install Python libraries"""

        # Ensure library isn't installed
        with self.assertRaises(ImportError):
            import html

        with open(REQUIREMENTS_TXT, 'wb') as file:
            file.write('html==1.15')

        # Install requirements
        AlfredBundler.init(REQUIREMENTS_TXT)

        # Correct version is installed
        import html
        self.assertTrue(html.__version__ == '1.15')
        self.assertTrue(os.path.exists(self.install_dir))

        # Update requirements with newer version
        with open(REQUIREMENTS_TXT, 'wb') as file:
            file.write('html==1.16')

        # Update installed libraries
        AlfredBundler.init(REQUIREMENTS_TXT)
        reload(html)
        self.assertTrue(html.__version__ == '1.16')

        # reset file
        with open(REQUIREMENTS_TXT, 'wb') as file:
            file.write('html==1.15')
Exemplo n.º 4
0
 def test_find_file(self):
     """Find file"""
     # Non-existent file
     with self.assertRaises(IOError):
         AlfredBundler._find_file('JX63OkRLRgcxUZ8ZAJQTaUksQPuGHUGt')
     # Existing file
     path = AlfredBundler._find_file('info.plist')
     self.assertEqual(os.path.abspath(path), os.path.abspath('info.plist'))
Exemplo n.º 5
0
    def test_dark_light_colors(self):
        """Dark and light colours"""
        black = '000'
        white = 'fff'
        self.assertTrue(AlfredBundler.color_is_dark(black))
        self.assertFalse(AlfredBundler.color_is_light(black))

        self.assertTrue(AlfredBundler.color_is_light(white))
        self.assertFalse(AlfredBundler.color_is_dark(white))
Exemplo n.º 6
0
    def test_convert_css_to_css2(self):
        """RGB -> HSV -> RGB"""

        for i in range(ITERATIONS):
            r = random.randint(0, 255)
            g = random.randint(0, 255)
            b = random.randint(0, 255)

            hsv = AlfredBundler.rgb_to_hsv(r, g, b)

            self.assertEqual((r, g, b), AlfredBundler.hsv_to_rgb(*hsv))
Exemplo n.º 7
0
 def test_asset(self):
     """Load asset"""
     path = os.path.join(DATA_DIR, 'assets', 'utility', 'Terminal-Notifier',
                         'latest', 'terminal-notifier.app', 'Contents',
                         'MacOS', 'terminal-notifier')
     self.assertEqual(AlfredBundler.utility('Terminal-Notifier', 'latest'),
                      path)
     self.assertEqual(AlfredBundler.asset('Terminal-Notifier', 'latest'),
                      path)
     self.assertEqual(AlfredBundler.utility('Terminal-Notifier'), path)
     self.assertEqual(AlfredBundler.asset('Terminal-Notifier'), path)
Exemplo n.º 8
0
 def test_system_icons(self):
     """System icons"""
     icondir = '/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources'
     good = ('Accounts', 'AirDrop', 'BookmarkIcon')
     bad = ('WindowLicker', 'Wolpertinger')
     for name in good:
         path = os.path.join(icondir, '{}.icns'.format(name))
         icon = AlfredBundler.icon('system', name)
         self.assertEqual(icon, path)
     for name in bad:
         with self.assertRaises(ValueError):
             AlfredBundler.icon('system', name)
Exemplo n.º 9
0
    def test_rgba_colors(self):
        """RGBA colours"""
        pairs = [
            ('rgba(255,255,255,1.0)', (255, 255, 255)),
            ('rgba(0,0,0,1.0)', (0, 0, 0)),
        ]

        for rgba, expected in pairs:
            self.assertEqual(expected, AlfredBundler.rgba_to_rgb(rgba))

        with self.assertRaises(ValueError):
            AlfredBundler.rgba_to_rgb('panties')
Exemplo n.º 10
0
    def test_pip_path(self):
        """Pip path"""
        # Delete pip and remove it from `sys.path`
        pip_path = os.path.join(HELPER_DIR, 'pip')
        if os.path.exists(pip_path):
            shutil.rmtree(pip_path)

        if HELPER_DIR in sys.path:
            sys.path.remove(HELPER_DIR)

        # Install pip and add its path to `sys.path`
        AlfredBundler._add_pip_path()
        self.assertTrue(HELPER_DIR in sys.path)
Exemplo n.º 11
0
    def test_update(self):
        """Bundler update"""

        # `_update()` exits if `update_running` == `True`
        AlfredBundler.metadata._last_updated = 0
        AlfredBundler.update_running = True
        AlfredBundler._update()
        self.assertEqual(AlfredBundler.metadata.get_updated(), 0)
        AlfredBundler.update_running = False

        # `_update()` exits if recently updated
        now = time.time()
        AlfredBundler.metadata._last_updated = now
        AlfredBundler._update()
        self.assertEqual(AlfredBundler.metadata.get_updated(), now)

        # Run actual update
        AlfredBundler.metadata._last_updated = 0
        AlfredBundler._update()

        # Metadata updated
        self.assertTrue(AlfredBundler.metadata.get_updated() > 0)

        # Update script fails
        script = AlfredBundler.BUNDLER_UPDATE_SCRIPT
        AlfredBundler.BUNDLER_UPDATE_SCRIPT = 'nonexistant-program'
        AlfredBundler.metadata._last_updated = 0
        AlfredBundler._update()

        AlfredBundler.BUNDLER_UPDATE_SCRIPT = script
Exemplo n.º 12
0
    def test_background(self):
        """Theme background"""
        # Test against `alfred_theme_background` set in
        # `setUp()`
        self.assertTrue(AlfredBundler.background_is_light())
        self.assertFalse(AlfredBundler.background_is_dark())

        # Change background to black
        os.environ['alfred_theme_background'] = 'rgba(0,0,0,1.0)'

        self.assertTrue(AlfredBundler.background_is_dark())
        self.assertFalse(AlfredBundler.background_is_light())

        # Test fallback background value from file
        del os.environ['alfred_theme_background']

        with open(BACKGROUND_COLOUR_FILE, 'wb') as file:
            file.write('light')

        self.assertTrue(AlfredBundler.background_is_light())
        self.assertFalse(AlfredBundler.background_is_dark())

        with open(BACKGROUND_COLOUR_FILE, 'wb') as file:
            file.write('dark')

        self.assertTrue(AlfredBundler.background_is_dark())
        self.assertFalse(AlfredBundler.background_is_light())
Exemplo n.º 13
0
    def _make_cell(color, font=DEMO_FONT, icon=DEMO_ICON, status=False):
        class_ = ('dark', 'light')[bundler.color_is_dark(color)]
        if status:
            width = '32'
        else:
            width = '128'
        icon = bundler.icon(font, icon, color)

        buffer = ['\t<td class="{}">'.format(class_)]
        buffer.append('\t\t<img width="{}" src="{}"/>'.format(width, icon))
        if not status:
            buffer.append('\t\t<p class="colour">#{}</p>'.format(color))
        buffer.append('\t</td>')

        return '\n'.join(buffer)
Exemplo n.º 14
0
    def test_logger(self):
        """Logger"""
        bid = AlfredBundler._bundle_id()
        logpath = os.path.join(
            os.path.expanduser(
                '~/Library/Application Support/Alfred 2/Workflow Data/'), bid,
            'logs', '{}.log'.format(bid))
        logdir = os.path.dirname(logpath)

        # Ensure directory is created
        if os.path.exists(logdir):
            shutil.rmtree(logdir)

        l = AlfredBundler.logger('demo')
        l.debug('test message')
        self.assertTrue(os.path.exists(logpath))
Exemplo n.º 15
0
    def test_round_trip_css(self):
        """CSS -> RGB -> HSV -> RGB -> CSS"""

        for i in range(ITERATIONS):
            r = random.randint(0, 255)
            g = random.randint(0, 255)
            b = random.randint(0, 255)

            css = '{:02x}{:02x}{:02x}'.format(r, g, b)

            hsv = AlfredBundler.rgb_to_hsv(r, g, b)
            r2, g2, b2 = AlfredBundler.hsv_to_rgb(*hsv)

            self.assertEqual((r, g, b), (r2, g2, b2))

            self.assertEqual(css, AlfredBundler.rgb_to_hex(r2, g2, b2))
Exemplo n.º 16
0
 def test_makedir(self):
     """Create metadata dir"""
     dirpath = os.path.dirname(UPDATE_JSON_PATH)
     if os.path.exists(dirpath):
         shutil.rmtree(dirpath)
     m2 = AlfredBundler.Metadata(UPDATE_JSON_PATH)
     m2.set_updated()
     self.assertTrue(os.path.exists(dirpath))
Exemplo n.º 17
0
    def notest_flip_round_trip(self):
        """CSS -> flip -> flip -> CSS"""

        for i in range(ITERATIONS):
            r = random.randint(0, 255)
            g = random.randint(0, 255)
            b = random.randint(0, 255)

            css = '{:02x}{:02x}{:02x}'.format(r, g, b)
            css2 = AlfredBundler.flip_color(AlfredBundler.flip_color(css))

            r2, g2, b2 = AlfredBundler.hex_to_rgb(css2)
            log.debug('{}  ->  {}'.format(css, css2))

            self.assertAlmostEquals(r, r2, delta=self.flip_distance)
            self.assertAlmostEquals(g, g2, delta=self.flip_distance)
            self.assertAlmostEquals(b, b2, delta=self.flip_distance)
Exemplo n.º 18
0
    def test_convert_css_to_css(self):
        """CSS -> RGB -> CSS"""

        for i in range(ITERATIONS):
            r = random.randint(0, 255)
            g = random.randint(0, 255)
            b = random.randint(0, 255)
            css = '{:02x}{:02x}{:02x}'.format(r, g, b)

            self.assertEqual(css, AlfredBundler.rgb_to_hex(r, g, b))
Exemplo n.º 19
0
    def test_convert_hex_rgb(self):
        """CSS -> RGB"""

        for i in range(ITERATIONS):
            r = random.randint(0, 255)
            g = random.randint(0, 255)
            b = random.randint(0, 255)
            css = '{:02x}{:02x}{:02x}'.format(r, g, b)
            rgb = (r, g, b)
            self.assertEqual(rgb, AlfredBundler.hex_to_rgb(css))
Exemplo n.º 20
0
    def test_etags(self):
        """Etags saved"""
        url = 'http://www.example.com'
        etag = 'nG8zqCNMWn1uPgLYl6qQiD'

        AlfredBundler.metadata.set_etag(url, etag)
        self.assertEqual(AlfredBundler.metadata.get_etag(url), etag)

        m2 = AlfredBundler.Metadata(UPDATE_JSON_PATH)
        self.assertEqual(m2.get_etag(url), etag)
Exemplo n.º 21
0
    def test_install_pip(self):
        """Install pip"""
        pip_path = os.path.join(HELPER_DIR, 'pip')
        installer_path = os.path.join(HELPER_DIR, 'get-pip.py')

        # Ensure pip isn't installed
        if os.path.exists(pip_path):
            shutil.rmtree(pip_path)

        if os.path.exists(UPDATE_JSON_PATH):
            os.unlink(UPDATE_JSON_PATH)

        # Test that updater removes old data
        pip_test_path = os.path.join(HELPER_DIR, 'pip-test')
        os.makedirs(pip_test_path, 0755)

        self.assertFalse(os.path.exists(pip_path))
        self.assertFalse(os.path.exists(installer_path))
        self.assertFalse(os.path.exists(UPDATE_JSON_PATH))

        # Install pip
        AlfredBundler.metadata.set_etag(PIP_INSTALLER_URL, 'blah')
        AlfredBundler._install_pip()
        # Pip installed
        self.assertTrue(os.path.exists(pip_path))
        # Installer was deleted
        self.assertFalse(os.path.exists(installer_path))
        # Metadata saved
        self.assertTrue(os.path.exists(UPDATE_JSON_PATH))

        # # Ensure pip is updated
        # AlfredBundler.metadata.set_etag(PIP_INSTALLER_URL, 'blah')
        # AlfredBundler._install_pip()
        # self.assertTrue(os.path.exists(pip_path))
        # self.assertFalse(os.path.exists(installer_path))
        # self.assertTrue(os.path.exists(UPDATE_JSON_PATH))

        # Old data was removed
        self.assertFalse(os.path.exists(pip_test_path))
Exemplo n.º 22
0
 def setUp(self):
     os.environ['alfred_theme_background'] = 'rgba(255,255,255,1.00)'
     self.tempdir = tempfile.mkdtemp()
     self.tempfile = os.path.join(self.tempdir,
                                  'test-{}.test'.format(os.getpid()))
     self.testurl = 'https://raw.githubusercontent.com/deanishe/alfred-workflow/master/README.md'
     self.badurl = 'http://eu.httpbin.org/status/201'
     self.install_dir = os.path.join(PYTHON_LIB_DIR,
                                     AlfredBundler._bundle_id())
     if os.path.exists(self.install_dir):
         shutil.rmtree(self.install_dir)
     if self.install_dir in sys.path:
         sys.path.remove(self.install_dir)
Exemplo n.º 23
0
    def test_icons(self):
        """Web icons"""
        # 404 for invalid font
        with self.assertRaises(urllib2.HTTPError):
            AlfredBundler.icon('spaff', 'adjust')

        # 404 for invalid character
        with self.assertRaises(urllib2.HTTPError):
            AlfredBundler.icon('fontawesome', 'banditry!')

        # ValueError for invalid colour
        with self.assertRaises(ValueError):
            AlfredBundler.icon('fontawesome', 'adjust', 'hubbahubba')

        # Ensure directories are created, valid icon is downloaded and returned
        path = os.path.join(ICON_CACHE, 'fontawesome', 'ffffff', 'adjust.png')
        dirpath = os.path.dirname(path)
        if os.path.exists(dirpath):
            shutil.rmtree(dirpath)

        icon = AlfredBundler.icon('fontawesome', 'adjust', 'fff')
        self.assertEqual(icon, path)
        self.assertTrue(os.path.exists(path))

        if os.path.exists(path):
            os.unlink(path)

        # Returns correctly altered icon. Here: dark icon on dark background
        # returns light icon instead
        os.environ['alfred_theme_background'] = 'rgba(0,0,0,1.0)'
        path = os.path.join(ICON_CACHE, 'fontawesome', 'ffffff',
                            'ambulance.png')
        icon = AlfredBundler.icon('fontawesome', 'ambulance', '000', True)

        self.assertEqual(icon, path)
        self.assertTrue(os.path.exists(path))

        # Icon is returned from cache
        icon = AlfredBundler.icon('fontawesome', 'ambulance', '000', True)
        self.assertEqual(icon, path)

        if os.path.exists(path):
            os.unlink(path)
Exemplo n.º 24
0
    def test_download(self):
        """Download"""
        # Download a file
        self.assertFalse(os.path.exists(self.tempfile))
        AlfredBundler._download_if_updated(self.testurl, self.tempfile)
        self.assertTrue(os.path.exists(self.tempfile))

        # Do not download unchanged file
        mtime = os.stat(self.tempfile).st_mtime
        AlfredBundler._download_if_updated(self.testurl, self.tempfile)
        self.assertEqual(os.stat(self.tempfile).st_mtime, mtime)

        # Do not download non-existent files if `ignore_missing` is `True`
        os.unlink(self.tempfile)
        AlfredBundler._download_if_updated(self.testurl,
                                           self.tempfile,
                                           ignore_missing=True)
        self.assertFalse(os.path.exists(self.tempfile))
        # self.assertTrue(os.path.exists(self.tempfile))

        # Exception raised when trying to download a bad URL
        with self.assertRaises(IOError):
            AlfredBundler._download_if_updated(self.badurl, self.tempfile)
Exemplo n.º 25
0
def main():

    if len(sys.argv) > 1:
        if sys.argv[1] in ('-h', '--help'):
            print(__doc__, file=sys.stderr)
            return

    lines = []

    def _make_cell(color, font=DEMO_FONT, icon=DEMO_ICON, status=False):
        class_ = ('dark', 'light')[bundler.color_is_dark(color)]
        if status:
            width = '32'
        else:
            width = '128'
        icon = bundler.icon(font, icon, color)

        buffer = ['\t<td class="{}">'.format(class_)]
        buffer.append('\t\t<img width="{}" src="{}"/>'.format(width, icon))
        if not status:
            buffer.append('\t\t<p class="colour">#{}</p>'.format(color))
        buffer.append('\t</td>')

        return '\n'.join(buffer)

    for i in range(ICON_COUNT):
        r = random.randint(0, 255)
        g = random.randint(0, 255)
        b = random.randint(0, 255)

        css1 = '{:02x}{:02x}{:02x}'.format(r, g, b)
        css2 = bundler.flip_color(css1)
        css3 = bundler.flip_color(css2)

        if css1 == css3:
            correct = True
        else:
            correct = False

        if correct:
            lines.append('<tr class="correct">')
        else:
            lines.append('<tr class="incorrect">')

        lines.append(_make_cell(css2))
        lines.append(_make_cell(css1))
        lines.append(_make_cell(css3))

        if correct:
            lines.append(_make_cell('2cd012', 'fontawesome', 'thumbs-up',
                                    True))
        else:
            lines.append(
                _make_cell('f22538', 'fontawesome', 'thumbs-down', True))

        lines.append('</tr>')

    content = '\n\t\t\t'.join(lines)

    print(TEMPLATE % dict(content=content,
                          bgdark=BG_DARK,
                          bglight=BG_LIGHT,
                          textlight=bundler.flip_color(BG_DARK),
                          textdark=bundler.flip_color(BG_LIGHT)))
Exemplo n.º 26
0
 def test_saving(self):
     """Update saved"""
     AlfredBundler.metadata.set_updated()
     m2 = AlfredBundler.Metadata(UPDATE_JSON_PATH)
     self.assertEqual(AlfredBundler.metadata.get_updated(),
                      m2.get_updated())