Ejemplo n.º 1
0
 def test_reporting_errors(self):
     #TODO:
     self.compile_bundles('webpack.config.error.js')
     try:
         get_loader(DEFAULT_CONFIG).get_bundle('main')
     except WebpackError as e:
         self.assertIn("Cannot resolve module 'the-library-that-did-not-exist'", str(e))
Ejemplo n.º 2
0
 def test_reporting_errors(self):
     self.compile_bundles('webpack.config.error.js')
     try:
         get_loader(DEFAULT_CONFIG).get_bundle('main')
     except WebpackError as e:
         self.assertIn("Can't resolve 'the-library-that-did-not-exist'",
                       str(e))
 def test_missing_bundle(self):
     missing_bundle_name = 'missing_bundle'
     self.compile_bundles('webpack.config.simple.js')
     try:
         get_loader(DEFAULT_CONFIG).get_bundle(missing_bundle_name)
     except WebpackBundleLookupError as e:
         self.assertIn('Cannot resolve bundle {0}'.format(missing_bundle_name), str(e))
Ejemplo n.º 4
0
 def test_missing_bundle(self):
     missing_bundle_name = 'missing_bundle'
     self.compile_bundles('webpack.config.simple.js')
     try:
         get_loader(DEFAULT_CONFIG).get_bundle(missing_bundle_name)
     except WebpackBundleLookupError as e:
         self.assertIn('Cannot resolve bundle {0}'.format(missing_bundle_name), str(e))
Ejemplo n.º 5
0
 def test_missing_entrypoint(self):
     missing_bundle_name = 'missing_entrypoint'
     self.compile_bundles('webpack.config.multipleEntrypoints.js')
     try:
         get_loader(DEFAULT_CONFIG).get_entry(missing_bundle_name)
     except WebpackBundleLookupError as e:
         self.assertIn(
             'Cannot resolve entry {0}'.format(missing_bundle_name), str(e))
Ejemplo n.º 6
0
 def test_bad_stats_url(self):
     stats_url = "http://example.testing.url.com/webpack-stats.json"
     try:
         get_loader(APP3).get_assets()
     except Exception as e:
         expected = ('Error downloading {0}. Are you sure the URL '
                     'is correct and your internet connection is '
                     'functioning?').format(stats_url)
         self.assertIn(expected, str(e))
Ejemplo n.º 7
0
 def test_invalid_assets_loader_function(self):
     config_name = 'APP_WITH_INVALID_ASSETS_LOADER'
     function_name = settings.WEBPACK_LOADER[config_name][
         'ASSETS_LOADER_FUNCTION']
     with self.assertRaisesMessage(
             expected_exception=WebpackError,
             expected_message=
         ("The ASSETS_LOADER_FUNCTION '{0}' specified in the {1} config "
          "could not be imported.").format(function_name, config_name),
     ):
         get_loader(config_name).get_assets()
Ejemplo n.º 8
0
 def test_missing_stats_file(self):
     stats_file = settings.WEBPACK_LOADER[DEFAULT_CONFIG]['STATS_FILE']
     if os.path.exists(stats_file):
         os.remove(stats_file)
     try:
         get_loader(DEFAULT_CONFIG).get_assets()
     except IOError as e:
         expected = (
             'Error reading {0}. Are you sure webpack has generated the '
             'file and the path is correct?').format(stats_file)
         self.assertIn(expected, str(e))
Ejemplo n.º 9
0
    def test_bad_status_in_production(self):
        with open(settings.WEBPACK_LOADER[DEFAULT_CONFIG]['STATS_FILE'],
                  'w') as stats_file:
            stats_file.write(json.dumps({'status': 'unexpected-status'}))

        try:
            get_loader(DEFAULT_CONFIG).get_bundle('main')
        except WebpackLoaderBadStatsError as e:
            self.assertIn(
                ("The stats file does not contain valid data. Make sure "
                 "webpack-bundle-tracker plugin is enabled and try to run"
                 " webpack again."), str(e))
Ejemplo n.º 10
0
 def test_missing_stats_file(self):
     stats_file = settings.WEBPACK_LOADER[DEFAULT_CONFIG]['STATS_FILE']
     if os.path.exists(stats_file):
         os.remove(stats_file)
     try:
         get_loader(DEFAULT_CONFIG).get_assets()
     except IOError as e:
         expected = (
             'Error reading {0}. Are you sure webpack has generated the '
             'file and the path is correct?'
         ).format(stats_file)
         self.assertIn(expected, str(e))
Ejemplo n.º 11
0
    def test_default_ignore_config_ignores_map_files(self):
        self.compile_bundles('webpack.config.sourcemaps.js')
        chunks = get_loader('NO_IGNORE_APP').get_bundle('main')
        has_map_files_chunks = any(
            [".map" in chunk["name"] for chunk in chunks])

        self.assertTrue(has_map_files_chunks)

        chunks = get_loader(DEFAULT_CONFIG).get_bundle('main')
        has_map_files_chunks = any(
            [".map" in chunk["name"] for chunk in chunks])

        self.assertFalse(has_map_files_chunks)
Ejemplo n.º 12
0
    def test_bad_status_in_production(self):
        with open(
            settings.WEBPACK_LOADER[DEFAULT_CONFIG]['STATS_FILE'], 'w'
        ) as stats_file:
            stats_file.write(json.dumps({'status': 'unexpected-status'}))

        try:
            get_loader(DEFAULT_CONFIG).get_bundle('main')
        except WebpackLoaderBadStatsError as e:
            self.assertIn((
                "The stats file does not contain valid data. Make sure "
                "webpack-bundle-tracker plugin is enabled and try to run"
                " webpack again."
            ), str(e))
Ejemplo n.º 13
0
def get_hue_bundles(app_name, config='DEFAULT'):
  '''
  Util function to get all bundles related to app_name including vendor bundles
  similar to get_bundle in https://github.com/django-webpack/django-webpack-loader/blob/master/webpack_loader/loader.py
  '''
  loader = get_loader(config)
  assets = loader.get_assets()

  if settings.DEBUG and assets.get('status') == 'compiling':
    timeout = loader.config['TIMEOUT'] or 0
    timed_out = False
    start = time.time()

    while assets.get('status') == 'compiling' and not timed_out:
      time.sleep(loader.config['POLL_INTERVAL'])
      if timeout and (time.time() - timeout > start):
        timed_out = True
      assets = loader.get_assets()

    if timed_out:
      raise WebpackLoaderTimeoutError(
        "Timed Out. Bundles for `{0}` took more than {1} seconds "
        "to compile.".format(app_name, timeout)
      )

  chunks = []
  if assets.get('status') == 'done':
    chunks = [chunk for chunk in assets['chunks'] if
              chunk.startswith(app_name) or
              chunk.startswith('vendors~' + app_name) or
              (not chunk.startswith('hue') and not chunk.startswith('vendors~hue') and app_name in chunk)]
    if not chunks:
      raise WebpackError("Failed to find bundles for `{0}` in config `{1}`".format(app_name, config))

  return chunks
Ejemplo n.º 14
0
    def test_assets_extract(self):
        self.compile_bundles('webpack.config.assets.js')

        assets = get_loader(DEFAULT_CONFIG).get_assets()
        self.assertEqual(assets['status'], 'done')
        self.assertIn('exported_assets', assets)

        assets = get_loader(DEFAULT_CONFIG).get_exported_asset('./test.png')
        images_diff = call([
            'diff',
            '/Users/devil/Contributions/django-webpack-loader/tests/assets/test.png',
            assets['path']
        ])
        self.assertEqual(images_diff, 0)
        self.assertEqual(
            assets['path'],
            os.path.join(settings.BASE_DIR,
                         'assets/bundles/' + assets['name']))
Ejemplo n.º 15
0
    def test_querystring(self):
        self.compile_bundles('webpack.config.queryString.js')
        loader = get_loader(DEFAULT_CONFIG)
        assets = loader.get_assets()
        self.assertEqual(assets['status'], 'done')

        main = list(loader.get_bundle('main'))
        self.assertEqual(len(main), 2)
        self.assertEqual(main[0]['publicPath'], 'http://custom-static-host.com/name.js?c08677af2765786cf3b7')
Ejemplo n.º 16
0
 def test_timeouts(self):
     with self.settings(DEBUG=True):
         with open(settings.WEBPACK_LOADER[DEFAULT_CONFIG]['STATS_FILE'],
                   'w') as stats_file:
             stats_file.write(json.dumps({'status': 'compiling'}))
         loader = get_loader(DEFAULT_CONFIG)
         loader.config['TIMEOUT'] = 0.1
         with self.assertRaises(WebpackLoaderTimeoutError):
             loader.get_bundle('main')
Ejemplo n.º 17
0
 def test_timeouts(self):
     with self.settings(DEBUG=True):
         with open(
             settings.WEBPACK_LOADER[DEFAULT_CONFIG]['STATS_FILE'], 'w'
         ) as stats_file:
             stats_file.write(json.dumps({'status': 'compiling'}))
         loader = get_loader(DEFAULT_CONFIG)
         loader.config['TIMEOUT'] = 0.1
         with self.assertRaises(WebpackLoaderTimeoutError):
             loader.get_bundle('main')
Ejemplo n.º 18
0
    def test_simple_and_css_extract(self):
        self.compile_bundles('webpack.config.simple.js')
        assets = get_loader(DEFAULT_CONFIG).get_assets()
        self.assertEqual(assets['status'], 'done')
        self.assertIn('chunks', assets)

        chunks = assets['chunks']
        self.assertIn('main', chunks)
        self.assertEqual(len(chunks), 1)

        main = chunks['main']
        self.assertEqual(main[0]['path'], os.path.join(settings.BASE_DIR, 'assets/bundles/main.js'))
        self.assertEqual(main[1]['path'], os.path.join(settings.BASE_DIR, 'assets/bundles/styles.css'))
Ejemplo n.º 19
0
    def test_js_gzip_extract(self):
        self.compile_bundles('webpack.config.gzipTest.js')
        assets = get_loader(DEFAULT_CONFIG).get_assets()
        self.assertEqual(assets['status'], 'done')
        self.assertIn('chunks', assets)

        chunks = assets['chunks']
        self.assertIn('main', chunks)
        self.assertEqual(len(chunks), 1)

        main = chunks['main']
        self.assertEqual(main[0]['path'], os.path.join(settings.BASE_DIR, 'assets/bundles/main.js.gz'))
        self.assertEqual(main[1]['path'], os.path.join(settings.BASE_DIR, 'assets/bundles/styles.css'))
Ejemplo n.º 20
0
 def test_bad_custom_loader(self):
     '''
     Tests that a bad custom loader path will raise an error
     '''
     loader_class = 'app.tests.bad_loader_path.BadCustomLoader'
     with self.settings(
             WEBPACK_LOADER={
                 'DEFAULT': {
                     'CACHE': False,
                     'BUNDLE_DIR_NAME': 'bundles/',
                     'LOADER_CLASS': loader_class
                 }
             }):
         self.reload_webpack()
         try:
             utils.get_loader(DEFAULT_CONFIG)
             self.fail(
                 'The loader should fail to load with a bad LOADER_CLASS')
         except ImportError as e:
             self.assertIn(
                 '{} doesn\'t look like a valid module path'.format(
                     loader_class), str(e))
Ejemplo n.º 21
0
    def test_code_spliting(self):
        self.compile_bundles('webpack.config.split.js')
        assets = get_loader(DEFAULT_CONFIG).get_assets()
        self.assertEqual(assets['status'], 'done')
        self.assertIn('chunks', assets)

        chunks = assets['chunks']
        self.assertIn('main', chunks)
        self.assertEquals(len(chunks), 1)

        files = assets['assets']
        self.assertEqual(files['main.js']['path'], os.path.join(settings.BASE_DIR, 'assets/bundles/main.js'))
        self.assertEqual(files['vendors.js']['path'], os.path.join(settings.BASE_DIR, 'assets/bundles/vendors.js'))
Ejemplo n.º 22
0
    def test_simple_and_css_extract(self):
        self.compile_bundles('webpack.config.simple.js')
        assets = get_loader(DEFAULT_CONFIG).get_assets()
        self.assertEqual(assets['status'], 'done')
        self.assertIn('chunks', assets)

        chunks = assets['chunks']
        self.assertIn('main', chunks)
        self.assertEqual(len(chunks), 1)

        files = assets['assets']
        self.assertEqual(files['main.css']['path'], os.path.join(settings.BASE_DIR, 'assets/bundles/main.css'))
        self.assertEqual(files['main.js']['path'], os.path.join(settings.BASE_DIR, 'assets/bundles/main.js'))
Ejemplo n.º 23
0
    def test_code_spliting(self):
        self.compile_bundles('webpack.config.split.js')
        assets = get_loader(DEFAULT_CONFIG).get_assets()
        self.assertEqual(assets['status'], 'done')
        self.assertIn('chunks', assets)

        chunks = assets['chunks']
        self.assertIn('main', chunks)
        self.assertEquals(len(chunks), 2)

        main = chunks['main']
        self.assertEqual(main[0]['path'], os.path.join(settings.BASE_DIR, 'assets/bundles/main.js'))

        vendor = chunks['vendor']
        self.assertEqual(vendor[0]['path'], os.path.join(settings.BASE_DIR, 'assets/bundles/vendor.js'))
Ejemplo n.º 24
0
 def test_good_custom_loader(self):
     '''
     Tests that a good custom loader will return the correct assets
     '''
     loader_class = 'app.tests.test_custom_loaders.ValidCustomLoader'
     with self.settings(
             WEBPACK_LOADER={
                 'DEFAULT': {
                     'CACHE': False,
                     'BUNDLE_DIR_NAME': 'bundles/',
                     'LOADER_CLASS': loader_class,
                 }
             }):
         self.reload_webpack()
         assets = utils.get_loader(DEFAULT_CONFIG).load_assets()
         self.assertEqual(assets, LOADER_PAYLOAD)
Ejemplo n.º 25
0
    def test_load_stats_from_url(self):
        self.compile_bundles('webpack.config.simple.js')
        stats_file = settings.WEBPACK_LOADER[DEFAULT_CONFIG]['STATS_FILE']
        stats_url = 'http://fake-s3.test/webpack-stats.json'

        # Load the content of the compiled webpack-stats.json as a mock url.
        with open(stats_file, 'r') as fp:
            responses.add(responses.GET,
                          stats_url,
                          body=fp.read(),
                          status=200,
                          content_type='application/json')

        assets = get_loader('FETCH_URL').get_assets()

        self.assertEqual(len(responses.calls), 1)
        self.assertEqual(assets['status'], 'done')
        self.assertIn('chunks', assets)
Ejemplo n.º 26
0
def _get_bundle(request, bundle_name):
    """
    Update bundle URLs to handle webpack hot reloading correctly if DEBUG=True

    Args:
        request (django.http.request.HttpRequest): A request
        bundle_name (str): The name of the webpack bundle

    Returns:
        iterable of dict:
            The chunks of the bundle. Usually there's only one but I suppose you could have
            CSS and JS chunks for one bundle for example
    """
    if not settings.DISABLE_WEBPACK_LOADER_STATS:
        for chunk in get_loader('DEFAULT').get_bundle(bundle_name):
            chunk_copy = dict(chunk)
            chunk_copy['url'] = "{host_url}/{bundle}".format(
                host_url=public_path(request).rstrip("/"),
                bundle=chunk['name'])
            yield chunk_copy
Ejemplo n.º 27
0
def _get_bundle(request, bundle_name):
    """
    Update bundle URLs to handle webpack hot reloading correctly if DEBUG=True

    Args:
        request (django.http.request.HttpRequest): A request
        bundle_name (str): The name of the webpack bundle

    Returns:
        iterable of dict:
            The chunks of the bundle. Usually there's only one but I suppose you could have
            CSS and JS chunks for one bundle for example
    """
    if not settings.DISABLE_WEBPACK_LOADER_STATS:
        for chunk in get_loader('DEFAULT').get_bundle(bundle_name):
            chunk_copy = dict(chunk)
            chunk_copy['url'] = "{host_url}/{bundle}".format(
                host_url=public_path(request).rstrip("/"),
                bundle=chunk['name']
            )
            yield chunk_copy
Ejemplo n.º 28
0
 def test_caching(self):
     loader = get_loader(CACHED_CONFIG)
     loader._load_assets = lambda: True
     self.assertIs(loader.get_assets(), True)
     loader._load_assets = lambda: False
     self.assertIs(loader.get_assets(), True)
Ejemplo n.º 29
0
def get_implementation(action_name):
    chunks = get_loader('ACTIONS').get_assets()['chunks']
    implementation_path = chunks[action_name][0]['path']
    with open(implementation_path) as f:
        return f.read()
Ejemplo n.º 30
0
 def test_static_url(self):
     self.compile_bundles('webpack.config.publicPath.js')
     assets = get_loader(DEFAULT_CONFIG).get_assets()
     self.assertEqual(assets['status'], 'done')
     self.assertEqual(assets['publicPath'], 'http://custom-static-host.com/')
Ejemplo n.º 31
0
def get_implementation(action_name):
    chunks = get_loader('ACTIONS').get_assets()['chunks']
    implementation_path = chunks[action_name][0]['path']
    with open(implementation_path) as f:
        return f.read()
Ejemplo n.º 32
0
 def test_default_asset_loader_function_config(self):
     config = get_loader(DEFAULT_CONFIG).config
     self.assertEqual(config['ASSETS_LOADER_FUNCTION'],
                      'webpack_loader.utils.load_assets_from_filesystem')
Ejemplo n.º 33
0
def get_implementation(action_name):
    chunks = get_loader("ACTIONS").get_assets()["chunks"]
    implementation_path = chunks[action_name][0]["path"]
    with open(implementation_path) as f:
        return f.read()
Ejemplo n.º 34
0
 def test_static_url(self):
     self.compile_bundles('webpack.config.publicPath.js')
     assets = get_loader(DEFAULT_CONFIG).get_assets()
     self.assertEqual(assets['status'], 'done')
     self.assertEqual(assets['publicPath'],
                      'http://custom-static-host.com/')
Ejemplo n.º 35
0
 def test_custom_asset_loader_function_is_called(self):
     loader = get_loader('APP_WITH_CUSTOM_ASSETS_LOADER')
     assets = loader.get_assets()
     self.assertDictEqual(assets, {'called_with': loader})