<commit_before>/*
 Description: The script is responsible for the implementing the client side logic;
    - Promoting an asset to the next stage of its life-cycle
    - Demoting an asset to the previous stage of its life-cycle
    - Obtaining the check list for a given state
    - Handling the click events associated with the check list items by calling the remote api responsible for
      ticking an asset check list item.
      Sources:
        Disabling a button with jQuery using disabled property
        http://stackoverflow.com/questions/1414365/how-to-disable-enable-an-input-with-jquery
 Filename: lifecycle.asset.js
 Created Date: 23/8/2013
 */

var onCheckListItemClick=function(){};
var sugyamaModule=sugyamaModule();
var sugyama=new sugyamaModule.Sugyama();

$(function(){

    /*
    Obtain the current url to get the id and asset type
     */
    var url=window.location.pathname;

    //Break the url into components
    var comps=url.split('/');

    //Given a url of the form /pub/api/asset/{asset-type}/{asset-id}
    //length=5
    //then: length-2 = {asset-type} length-1 = {asset-id}
    var id=comps[comps.length-1];
    var asset=comps[comps.length-2];

    console.log(asset);
    console.log(id);

    buildCheckList(asset,id);
    buildLCGraph();
    buildHistory(asset,id);

    /*
    Promotes an asset
     */
  /*  $('#btn-asset-promote').on('click',function(e){
    	e.preventDefault();
       console.log('/publisher/api/lifecycle/Promote/'+asset+'/'+id);
        $.ajax({
          url:'/publisher/api/lifecycle/Promote/'+asset+'/'+id,
          type:'PUT',
          success:function(response){
              showAlert('Asset promoted successfully', 'success');

              $.ajax({
                  url:'/publisher/api/lifecycle/'+asset+'/'+id,
                  type:'GET',
                  success:function(response){
                      var statInfo=JSON.parse(response);
                      $('#state').html(statInfo.state);
                      $('#view-lifecyclestate').html(statInfo.state);
                      //disableActions(statInfo.actions);
                      buildCheckList(asset,id);
                      buildLCGraph();
                      buildHistory(asset,id);
                  },
                  error:function(response){
                      $('#state').html('Error obtaining state');
                  }
              });
          },
          error:function(response){
			showAlert('Error occured while promoting', 'error');
          }
        });
    }); */

    /*
    Demotes an asset
     */
 /*   $('#btn-asset-demote').on('click',function(e){
    	e.preventDefault();
        $.ajax({
            url:'/publisher/api/lifecycle/Demote/'+asset+'/'+id,
            type:'PUT',
            success:function(response){
                showAlert('Asset demoted successfully', 'success');
                $.ajax({
                    url:'/publisher/api/lifecycle/'+asset+'/'+id,
                    type:'GET',
                    success:function(response){
                        //Convert the response to a JSON object
                        var statInfo=JSON.parse(response);

                        $('#state').html(statInfo.state);
                        $('#view-lifecyclestate').html(statInfo.state);
                        //disableActions(statInfo.actions);
                        buildCheckList(asset,id);
                        buildLCGraph();
                        buildHistory(asset,id);
                    },
                    error:function(response){
                        $('#state').html('Error obtaining life-cycle state of asset.');
                    }
                });
            },
            error:function(response){
               showAlert('Error occured while demoting', 'error');
            }
        });

    });*/

    /*
    The method only enables and disables the appropriate actions
     */
    function disableActions(actions){

        //Eagerly disable all of the buttons
        var buttons=['btn-asset-promote','btn-asset-demote'];

        for(var buttonIndex in buttons){
            var button=buttons[buttonIndex];
            $('#'+button).prop('disabled',true);
        }

        //Enable only relevant buttons.
        for(var actionIndex in actions){
            var action=actions[actionIndex];
            if(action=='Promote'){
                $('#btn-asset-promote').prop('disabled',false);
            }
            else if(action=='Demote'){
                $('#btn-asset-demote').prop('disabled',false);
            }
        }
    }

    /*
    The function builds the LC graph
     */
    function buildLCGraph(){
        $.ajax({
            url:'/publisher/api/lifecycle/'+asset+'/'+id,
            type:'GET',
            success:function(response){
                var element=$('#canvas');
                if(element){
                    var paper=new Raphael('canvas');
                    //element.html(response);

                   /* if(!graph.Renderer.config.canvas.canvasElement){

                        graph.Renderer.config.canvas.canvasElement=element;

                        graph.Renderer.initRaphael();
                        graph.Renderer.render(graph.NMap);
                    }       */
                    var statInfo=JSON.parse(response);
                    sugyama.init(statInfo.lifecycle,paper);
                    var START_X=10;
                    var START_Y=50;
                    var VERTEX_RADIUS=22;
                    var LAYER_SEP=85;
                    var LAYER_SPACE=200;
                    sugyama.draw(START_X,START_Y,VERTEX_RADIUS,LAYER_SPACE,LAYER_SEP);

                    //graph.Renderer.setSelected(statInfo.state);
                    disableActions(statInfo.actions);
                    buildButtons(statInfo.actions);
                    highlightTransition(statInfo.state);
                }
                //$('#canvas').html(response);
            },
            error:function(response){
                $('#canvas').html('Error obtaining life-cycle state of asset.');
            }
        });
    }

    /*
     The function encapsulates all of the logic which occurs when a user clicks a
     lifecycle button
     @action: The action for the button
     */
    function buttonClickLogic(action){
        $.ajax({
            url:'/publisher/api/lifecycle/'+action+'/'+asset+'/'+id,
            type:'PUT',
            success:function(response){
                showAlert('Asset demoted successfully', 'success');
                $.ajax({
                    url:'/publisher/api/lifecycle/'+asset+'/'+id,
                    type:'GET',
                    success:function(response){
                        //Convert the response to a JSON object
                        var statInfo=JSON.parse(response);

                        $('#state').html(statInfo.state);
                        $('#view-lifecyclestate').html(statInfo.state);
                        //disableActions(statInfo.actions);
                        buildCheckList(asset,id);
                        buildLCGraph();
                        buildHistory(asset,id);
                    },
                    error:function(response){
                        $('#state').html('Error obtaining life-cycle state of asset.');
                    }
                });
            },
            error:function(response){
                showAlert('Error occured while demoting', 'error');
            }
        });
    }

    /*
    The function is used to populate the buttons
    @actions: The actions available to the current state
     */
    function buildButtons(actions){

        //Obtain the button container
        var BUTTON_CONTAINER='#form-actions';

        //Clear the button container of previous buttons
        $(BUTTON_CONTAINER).html('');

        for(var index in actions){
            var action=actions[index];

            //Populate  buttons based on the action
            var element=document.createElement('input');
            element.type='button';
            element.value=action;
            element.className='btn btn-primary pull-right';
            element.id='btn'+action;

            $(BUTTON_CONTAINER).append(element);
            $('#btn'+action).on('click',function(e){
                var clicked=e.target.value;
                e.preventDefault();
                buttonClickLogic(clicked);
            });
        }
    }

    /*
    The function is used to build the representation of the check list.
     */
    function buildCheckList(asset,id){

        //Check if the id exists before making a call
        if((asset=='')||(id=='')){
            console.log('omitting');
            return;
        }

        //Clear the checklist rendering area
        $('#checklist').html('');

        //Make a call to the lifecycle check list
        $.ajax({
            url:'/publisher/api/lifecycle/checklist/'+asset+'/'+id,
            type:'GET',
            success:function(response){

                var out='
';

                var obj=JSON.parse(response);

                for(var index in obj.checkListItems){

                   var current=obj.checkListItems[index];

                   out+='
<input type="checkbox" onclick="onCheckListItemClick(this,'+index+')" ';

                   if(current.checked){
                        out+='checked';
                   }

                   out+='>'+current.name+'
';
                }

                out+='
';

                //Render the check list
                $('#checklist').html(out);
            }

        });
    }

    /*
    The function obtains the history information about the life-cycle changes
     */
    function buildHistory(asset,id){
        var version='1.0.0';
        //Make a call to the api to obtain the history
        var path='/publisher/api/lifecycle/information/history/'+asset+'/'+id+'/'+version;
        $.ajax({
            url:path,
            type:'GET',
            success:function(response){
                //console.log(response);
                var obj=JSON.parse(response);
                var out=createHistoryEntry(obj.item);
                $('#lc-history').html(out);
            },
            error:function(response){
               // console.log('lc history not retrieved');
            }
        });
    }

    function createHistoryEntry(items){
        var output='';

        for(var itemIndex in items){
            output+='
';
            output+=' '+items[itemIndex].timestamp+'	';
            output+=''+items[itemIndex].user+' changed the asset from '+items[itemIndex].state
            +' to '+items[itemIndex].targetState + '	';
            output+='
';
        }

        return output;
    }

    /*
    Click handler which detects when a check list item is clicked
     */
    function onCheckListItemClickHandler(checkbox,index){

        if(checkbox.checked){
            callCheckListItem(checkbox,index);
        }
        else{
            callUncheckListItem(checkbox,index);
        }
    }
    /*
    The function checks a life-cycle check list item by calling the checklist api method
     */
    function callCheckListItem(checkbox,checkListItemIndex){
        $.ajax({
            url:'/publisher/api/lifecycle/checklistitem/'+checkListItemIndex+'/'+asset+'/'+id,
            type:'POST',
            success:function(response){
                alert('Item checked successfully');
            },
            error:function(response){
                checkbox.checked=false; //Revert the checkbox to the previous state
                alert('Could not check item');
            }
        });
    }

    /*
    The function unchecks a life-cycle check list item by calling the checklist api method
     */
    function callUncheckListItem(checkbox,checkListItemIndex){
        $.ajax({
            url:'/publisher/api/lifecycle/checklistitem/'+checkListItemIndex+'/'+asset+'/'+id,
            type:'DELETE',
            success:function(response){
                alert('Item unchecked successfully');
            },
            error:function(response){
                checkbox.checked=true;  //Revert the checkbox to previous state
                alert('Could not uncheck item');
            }
        });
    }

    function showAlert(msg, type){
    	var alert = $('.widget-content .alert');
    	alert.removeClass().addClass('info-div alert alert-' + type).find('span').text(msg);
    	alert.delay(1000).fadeIn("fast").delay(2000).fadeOut("fast");
    }

	function highlightTransition(state){
      var elem = $('.'+state);
      elem.attr('fill', '#52B9E9');
      //$('#canvas').attr('data-current', state);
    }
   /*
   Click handlers for the checkboxes
    */
   onCheckListItemClick=onCheckListItemClickHandler;

});<commit_msg>Fixed the lifecycle actions to be relevant instead<commit_after>/*
 Description: The script is responsible for the implementing the client side logic;
    - Promoting an asset to the next stage of its life-cycle
    - Demoting an asset to the previous stage of its life-cycle
    - Obtaining the check list for a given state
    - Handling the click events associated with the check list items by calling the remote api responsible for
      ticking an asset check list item.
      Sources:
        Disabling a button with jQuery using disabled property
        http://stackoverflow.com/questions/1414365/how-to-disable-enable-an-input-with-jquery
 Filename: lifecycle.asset.js
 Created Date: 23/8/2013
 */

var onCheckListItemClick=function(){};
var sugyamaModule=sugyamaModule();
var sugyama=new sugyamaModule.Sugyama();

$(function(){

    /*
    Obtain the current url to get the id and asset type
     */
    var url=window.location.pathname;

    //Break the url into components
    var comps=url.split('/');

    //Given a url of the form /pub/api/asset/{asset-type}/{asset-id}
    //length=5
    //then: length-2 = {asset-type} length-1 = {asset-id}
    var id=comps[comps.length-1];
    var asset=comps[comps.length-2];

    console.log(asset);
    console.log(id);

    buildCheckList(asset,id);
    buildLCGraph();
    buildHistory(asset,id);

    /*
    Promotes an asset
     */
  /*  $('#btn-asset-promote').on('click',function(e){
    	e.preventDefault();
       console.log('/publisher/api/lifecycle/Promote/'+asset+'/'+id);
        $.ajax({
          url:'/publisher/api/lifecycle/Promote/'+asset+'/'+id,
          type:'PUT',
          success:function(response){
              showAlert('Asset promoted successfully', 'success');

              $.ajax({
                  url:'/publisher/api/lifecycle/'+asset+'/'+id,
                  type:'GET',
                  success:function(response){
                      var statInfo=JSON.parse(response);
                      $('#state').html(statInfo.state);
                      $('#view-lifecyclestate').html(statInfo.state);
                      //disableActions(statInfo.actions);
                      buildCheckList(asset,id);
                      buildLCGraph();
                      buildHistory(asset,id);
                  },
                  error:function(response){
                      $('#state').html('Error obtaining state');
                  }
              });
          },
          error:function(response){
			showAlert('Error occured while promoting', 'error');
          }
        });
    }); */

    /*
    Demotes an asset
     */
 /*   $('#btn-asset-demote').on('click',function(e){
    	e.preventDefault();
        $.ajax({
            url:'/publisher/api/lifecycle/Demote/'+asset+'/'+id,
            type:'PUT',
            success:function(response){
                showAlert('Asset demoted successfully', 'success');
                $.ajax({
                    url:'/publisher/api/lifecycle/'+asset+'/'+id,
                    type:'GET',
                    success:function(response){
                        //Convert the response to a JSON object
                        var statInfo=JSON.parse(response);

                        $('#state').html(statInfo.state);
                        $('#view-lifecyclestate').html(statInfo.state);
                        //disableActions(statInfo.actions);
                        buildCheckList(asset,id);
                        buildLCGraph();
                        buildHistory(asset,id);
                    },
                    error:function(response){
                        $('#state').html('Error obtaining life-cycle state of asset.');
                    }
                });
            },
            error:function(response){
               showAlert('Error occured while demoting', 'error');
            }
        });

    });*/

    /*
    The method only enables and disables the appropriate actions
     */
    function disableActions(actions){

        //Eagerly disable all of the buttons
        var buttons=['btn-asset-promote','btn-asset-demote'];

        for(var buttonIndex in buttons){
            var button=buttons[buttonIndex];
            $('#'+button).prop('disabled',true);
        }

        //Enable only relevant buttons.
        for(var actionIndex in actions){
            var action=actions[actionIndex];
            if(action=='Promote'){
                $('#btn-asset-promote').prop('disabled',false);
            }
            else if(action=='Demote'){
                $('#btn-asset-demote').prop('disabled',false);
            }
        }
    }

    /*
    The function builds the LC graph
     */
    function buildLCGraph(){
        $.ajax({
            url:'/publisher/api/lifecycle/'+asset+'/'+id,
            type:'GET',
            success:function(response){
                var element=$('#canvas');
                if(element){
                    var paper=new Raphael('canvas');
                    //element.html(response);

                   /* if(!graph.Renderer.config.canvas.canvasElement){

                        graph.Renderer.config.canvas.canvasElement=element;

                        graph.Renderer.initRaphael();
                        graph.Renderer.render(graph.NMap);
                    }       */
                    var statInfo=JSON.parse(response);
                    sugyama.init(statInfo.lifecycle,paper);
                    var START_X=10;
                    var START_Y=50;
                    var VERTEX_RADIUS=22;
                    var LAYER_SEP=85;
                    var LAYER_SPACE=200;
                    sugyama.draw(START_X,START_Y,VERTEX_RADIUS,LAYER_SPACE,LAYER_SEP);

                    //graph.Renderer.setSelected(statInfo.state);
                    disableActions(statInfo.actions);
                    buildButtons(statInfo.actions);
                    highlightTransition(statInfo.state);
                }
                //$('#canvas').html(response);
            },
            error:function(response){
                $('#canvas').html('Error obtaining life-cycle state of asset.');
            }
        });
    }

    /*
     The function encapsulates all of the logic which occurs when a user clicks a
     lifecycle button
     @action: The action for the button
     */
    function buttonClickLogic(action){
        $.ajax({
            url:'/publisher/api/lifecycle/'+action+'/'+asset+'/'+id,
            type:'PUT',
            success:function(response){
                var actionName=action.toLowerCase();
                actionName+='d';
                showAlert('Asset was '+actionName+' successfully.', 'success');
                $.ajax({
                    url:'/publisher/api/lifecycle/'+asset+'/'+id,
                    type:'GET',
                    success:function(response){
                        //Convert the response to a JSON object
                        var statInfo=JSON.parse(response);

                        $('#state').html(statInfo.state);
                        $('#view-lifecyclestate').html(statInfo.state);
                        //disableActions(statInfo.actions);
                        buildCheckList(asset,id);
                        buildLCGraph();
                        buildHistory(asset,id);
                    },
                    error:function(response){
                        $('#state').html('Error obtaining life-cycle state of asset.');
                    }
                });
            },
            error:function(response){
                showAlert('Error occured while demoting', 'error');
            }
        });
    }

    /*
    The function is used to populate the buttons
    @actions: The actions available to the current state
     */
    function buildButtons(actions){

        //Obtain the button container
        var BUTTON_CONTAINER='#form-actions';

        //Clear the button container of previous buttons
        $(BUTTON_CONTAINER).html('');

        for(var index in actions){
            var action=actions[index];

            //Populate  buttons based on the action
            var element=document.createElement('input');
            element.type='button';
            element.value=action;
            element.className='btn btn-primary pull-right';
            element.id='btn'+action;

            $(BUTTON_CONTAINER).append(element);
            $('#btn'+action).on('click',function(e){
                var clicked=e.target.value;
                e.preventDefault();
                buttonClickLogic(clicked);
            });
        }
    }

    /*
    The function is used to build the representation of the check list.
     */
    function buildCheckList(asset,id){

        //Check if the id exists before making a call
        if((asset=='')||(id=='')){
            console.log('omitting');
            return;
        }

        //Clear the checklist rendering area
        $('#checklist').html('');

        //Make a call to the lifecycle check list
        $.ajax({
            url:'/publisher/api/lifecycle/checklist/'+asset+'/'+id,
            type:'GET',
            success:function(response){

                var out='
';

                var obj=JSON.parse(response);

                for(var index in obj.checkListItems){

                   var current=obj.checkListItems[index];

                   out+='
<input type="checkbox" onclick="onCheckListItemClick(this,'+index+')" ';

                   if(current.checked){
                        out+='checked';
                   }

                   out+='>'+current.name+'
';
                }

                out+='
';

                //Render the check list
                $('#checklist').html(out);
            }

        });
    }

    /*
    The function obtains the history information about the life-cycle changes
     */
    function buildHistory(asset,id){
        var version='1.0.0';
        //Make a call to the api to obtain the history
        var path='/publisher/api/lifecycle/information/history/'+asset+'/'+id+'/'+version;
        $.ajax({
            url:path,
            type:'GET',
            success:function(response){
                //console.log(response);
                var obj=JSON.parse(response);
                var out=createHistoryEntry(obj.item);
                $('#lc-history').html(out);
            },
            error:function(response){
               // console.log('lc history not retrieved');
            }
        });
    }

    function createHistoryEntry(items){
        var output='';

        for(var itemIndex in items){
            output+='
';
            output+=' '+items[itemIndex].timestamp+'	';
            output+=''+items[itemIndex].user+' changed the asset from '+items[itemIndex].state
            +' to '+items[itemIndex].targetState + '	';
            output+='
';
        }

        return output;
    }

    /*
    Click handler which detects when a check list item is clicked
     */
    function onCheckListItemClickHandler(checkbox,index){

        if(checkbox.checked){
            callCheckListItem(checkbox,index);
        }
        else{
            callUncheckListItem(checkbox,index);
        }
    }
    /*
    The function checks a life-cycle check list item by calling the checklist api method
     */
    function callCheckListItem(checkbox,checkListItemIndex){
        $.ajax({
            url:'/publisher/api/lifecycle/checklistitem/'+checkListItemIndex+'/'+asset+'/'+id,
            type:'POST',
            success:function(response){
                alert('Item checked successfully');
            },
            error:function(response){
                checkbox.checked=false; //Revert the checkbox to the previous state
                alert('Could not check item');
            }
        });
    }

    /*
    The function unchecks a life-cycle check list item by calling the checklist api method
     */
    function callUncheckListItem(checkbox,checkListItemIndex){
        $.ajax({
            url:'/publisher/api/lifecycle/checklistitem/'+checkListItemIndex+'/'+asset+'/'+id,
            type:'DELETE',
            success:function(response){
                alert('Item unchecked successfully');
            },
            error:function(response){
                checkbox.checked=true;  //Revert the checkbox to previous state
                alert('Could not uncheck item');
            }
        });
    }

    function showAlert(msg, type){
    	var alert = $('.widget-content .alert');
    	alert.removeClass().addClass('info-div alert alert-' + type).find('span').text(msg);
    	alert.delay(1000).fadeIn("fast").delay(2000).fadeOut("fast");
    }

	function highlightTransition(state){
      var elem = $('.'+state);
      elem.attr('fill', '#52B9E9');
      //$('#canvas').attr('data-current', state);
    }
   /*
   Click handlers for the checkboxes
    */
   onCheckListItemClick=onCheckListItemClickHandler;

});<|endoftext|>


<commit_before>const Uppy = require('uppy/lib/core/Core')
const Dashboard = require('uppy/lib/plugins/Dashboard')
const Webcam = require('uppy/lib/plugins/Webcam')
const Transloadit = require('uppy/lib/plugins/Transloadit')
const Instagram = require('uppy/lib/plugins/Instagram')

function initUppy () {
  if (window.uppy) {
    window.uppy.close()
  }

  const uppy = Uppy({
    debug: true,
    autoProceed: false,
    restrictions: {
      maxFileSize: 1024 * 1024 * 1024,
      maxNumberOfFiles: 2,
      minNumberOfFiles: 1,
      allowedFileTypes: ['image/*']
    }
  })

  uppy
    .use(Transloadit, {
      params: {
        auth: {
          key: window.TRANSLOADIT_API_KEY
        },
        // It's more secure to use a template_id and enable
        // Signature Authentication
        steps: {
          resize: {
            robot: '/image/resize',
            width: 250,
            height: 250,
            resize_strategy: 'fit',
            text: [
              {
                text: '© 2018 Transloadit.com',
                size: 12,
                font: 'Ubuntu',
                color: '#eeeeee',
                valign: 'bottom',
                align: 'right',
                x_offset: 16,
                y_offset: -10
              }
            ]
          }
        }
      },
      waitForEncoding: true
    })
    .use(Dashboard, {
      inline: true,
      maxHeight: 400,
      target: '#uppy-dashboard-container',
      note: 'Images and video only, 1–2 files, up to 1 MB'
    })
    .use(Instagram, { target: Dashboard, host: 'https://api2.transloadit.com/uppy-server' })
    .use(Webcam, { target: Dashboard })

  uppy
    .on('transloadit:result', (stepName, result) => {
      const file = uppy.getFile(result.localId)
      var resultContainer = document.createElement('div')
      resultContainer.innerHTML = `

Name: ${file.name}

          View

      `
      document
        .getElementById('uppy-transloadit-result')
        .appendChild(resultContainer)
    })
}

window.initUppy = initUppy
<commit_msg>fix note in transloadit example<commit_after>const Uppy = require('uppy/lib/core/Core')
const Dashboard = require('uppy/lib/plugins/Dashboard')
const Webcam = require('uppy/lib/plugins/Webcam')
const Transloadit = require('uppy/lib/plugins/Transloadit')
const Instagram = require('uppy/lib/plugins/Instagram')

function initUppy () {
  if (window.uppy) {
    window.uppy.close()
  }

  const uppy = Uppy({
    debug: true,
    autoProceed: false,
    restrictions: {
      maxFileSize: 1024 * 1024 * 1024,
      maxNumberOfFiles: 2,
      minNumberOfFiles: 1,
      allowedFileTypes: ['image/*']
    }
  })

  uppy
    .use(Transloadit, {
      params: {
        auth: {
          key: window.TRANSLOADIT_API_KEY
        },
        // It's more secure to use a template_id and enable
        // Signature Authentication
        steps: {
          resize: {
            robot: '/image/resize',
            width: 250,
            height: 250,
            resize_strategy: 'fit',
            text: [
              {
                text: '© 2018 Transloadit.com',
                size: 12,
                font: 'Ubuntu',
                color: '#eeeeee',
                valign: 'bottom',
                align: 'right',
                x_offset: 16,
                y_offset: -10
              }
            ]
          }
        }
      },
      waitForEncoding: true
    })
    .use(Dashboard, {
      inline: true,
      maxHeight: 400,
      target: '#uppy-dashboard-container',
      note: 'Images only, 1–2 files, up to 1 MB'
    })
    .use(Instagram, { target: Dashboard, host: 'https://api2.transloadit.com/uppy-server' })
    .use(Webcam, { target: Dashboard })

  uppy
    .on('transloadit:result', (stepName, result) => {
      const file = uppy.getFile(result.localId)
      var resultContainer = document.createElement('div')
      resultContainer.innerHTML = `

Name: ${file.name}

          View

      `
      document
        .getElementById('uppy-transloadit-result')
        .appendChild(resultContainer)
    })
}

window.initUppy = initUppy
<|endoftext|>


<commit_before>
var lexers = require('../lib/lexer');
var TokenType = lexers.TokenType;

exports['Create lexer'] = function (test) {
    var lexer = lexers.lexer('foo');

    test.ok(lexer);
    test.equal(typeof lexer, 'object');
};

exports['Get name'] = function (test) {
    var lexer = lexers.lexer('foo');

    var token = lexer.nextToken();

    test.ok(token);
    test.equal(token.type, TokenType.Name);
    test.equal(token.value, 'foo');

    test.strictEqual(lexer.nextToken(), null);
};

exports['Get name with spaces'] = function (test) {
    var lexer = lexers.lexer('  foo   ');

    var token = lexer.nextToken();

    test.ok(token);
    test.equal(token.type, TokenType.Name);
    test.equal(token.value, 'foo');

    test.strictEqual(lexer.nextToken(), null);
};

exports['Get name skipping commas'] = function (test) {
    var lexer = lexers.lexer('  ,,foo,,, ');

    var token = lexer.nextToken();

    test.ok(token);
    test.equal(token.type, TokenType.Name);
    test.equal(token.value, 'foo');

    test.strictEqual(lexer.nextToken(), null);
};

exports['Get names'] = function (test) {
    var lexer = lexers.lexer('foo bar');

    var token = lexer.nextToken();

    test.ok(token);
    test.equal(token.type, TokenType.Name);
    test.equal(token.value, 'foo');

    var token = lexer.nextToken();

    test.ok(token);
    test.equal(token.type, TokenType.Name);
    test.equal(token.value, 'bar');

    test.strictEqual(lexer.nextToken(), null);
};

exports['Get string'] = function (test) {
    var lexer = lexers.lexer('"foo"');

    var token = lexer.nextToken();

    test.ok(token);
    test.equal(token.type, TokenType.String);
    test.equal(token.value, 'foo');

    test.strictEqual(lexer.nextToken(), null);
};

exports['Get integer'] = function (test) {
    var lexer = lexers.lexer('42');

    var token = lexer.nextToken();

    test.ok(token);
    test.equal(token.type, TokenType.Integer);
    test.equal(token.value, '42');

    test.strictEqual(lexer.nextToken(), null);
};

exports['Get parenthesis as delimiter'] = function (test) {
    var lexer = lexers.lexer('()');

    var token = lexer.nextToken();

    test.ok(token);
    test.equal(token.type, TokenType.Delimiter);
    test.equal(token.value, '(');

    var token = lexer.nextToken();

    test.ok(token);
    test.equal(token.type, TokenType.Delimiter);
    test.equal(token.value, ')');

    test.strictEqual(lexer.nextToken(), null);
};

exports['Get square brackets as delimiters'] = function (test) {
    var lexer = lexers.lexer('[]');

    var token = lexer.nextToken();

    test.ok(token);
    test.equal(token.type, TokenType.Delimiter);
    test.equal(token.value, '[');

    var token = lexer.nextToken();

    test.ok(token);
    test.equal(token.type, TokenType.Delimiter);
    test.equal(token.value, ']');

    test.strictEqual(lexer.nextToken(), null);
};
<commit_msg>Additional test, lexer get name with qualified namespace<commit_after>
var lexers = require('../lib/lexer');
var TokenType = lexers.TokenType;

exports['Create lexer'] = function (test) {
    var lexer = lexers.lexer('foo');

    test.ok(lexer);
    test.equal(typeof lexer, 'object');
};

exports['Get name'] = function (test) {
    var lexer = lexers.lexer('foo');

    var token = lexer.nextToken();

    test.ok(token);
    test.equal(token.type, TokenType.Name);
    test.equal(token.value, 'foo');

    test.strictEqual(lexer.nextToken(), null);
};

exports['Get name with qualified namespace'] = function (test) {
    var lexer = lexers.lexer('cljs.core/foo');

    var token = lexer.nextToken();

    test.ok(token);
    test.equal(token.type, TokenType.Name);
    test.equal(token.value, 'cljs.core/foo');

    test.strictEqual(lexer.nextToken(), null);
};

exports['Get name with spaces'] = function (test) {
    var lexer = lexers.lexer('  foo   ');

    var token = lexer.nextToken();

    test.ok(token);
    test.equal(token.type, TokenType.Name);
    test.equal(token.value, 'foo');

    test.strictEqual(lexer.nextToken(), null);
};

exports['Get name skipping commas'] = function (test) {
    var lexer = lexers.lexer('  ,,foo,,, ');

    var token = lexer.nextToken();

    test.ok(token);
    test.equal(token.type, TokenType.Name);
    test.equal(token.value, 'foo');

    test.strictEqual(lexer.nextToken(), null);
};

exports['Get names'] = function (test) {
    var lexer = lexers.lexer('foo bar');

    var token = lexer.nextToken();

    test.ok(token);
    test.equal(token.type, TokenType.Name);
    test.equal(token.value, 'foo');

    var token = lexer.nextToken();

    test.ok(token);
    test.equal(token.type, TokenType.Name);
    test.equal(token.value, 'bar');

    test.strictEqual(lexer.nextToken(), null);
};

exports['Get string'] = function (test) {
    var lexer = lexers.lexer('"foo"');

    var token = lexer.nextToken();

    test.ok(token);
    test.equal(token.type, TokenType.String);
    test.equal(token.value, 'foo');

    test.strictEqual(lexer.nextToken(), null);
};

exports['Get integer'] = function (test) {
    var lexer = lexers.lexer('42');

    var token = lexer.nextToken();

    test.ok(token);
    test.equal(token.type, TokenType.Integer);
    test.equal(token.value, '42');

    test.strictEqual(lexer.nextToken(), null);
};

exports['Get parenthesis as delimiter'] = function (test) {
    var lexer = lexers.lexer('()');

    var token = lexer.nextToken();

    test.ok(token);
    test.equal(token.type, TokenType.Delimiter);
    test.equal(token.value, '(');

    var token = lexer.nextToken();

    test.ok(token);
    test.equal(token.type, TokenType.Delimiter);
    test.equal(token.value, ')');

    test.strictEqual(lexer.nextToken(), null);
};

exports['Get square brackets as delimiters'] = function (test) {
    var lexer = lexers.lexer('[]');

    var token = lexer.nextToken();

    test.ok(token);
    test.equal(token.type, TokenType.Delimiter);
    test.equal(token.value, '[');

    var token = lexer.nextToken();

    test.ok(token);
    test.equal(token.type, TokenType.Delimiter);
    test.equal(token.value, ']');

    test.strictEqual(lexer.nextToken(), null);
};
<|endoftext|>


<commit_before>// RUN TEST USING:
// pushd ts && tsc && popd && node test.js

var fs = require("fs");
var vm = require("vm");

function include(path) {
    var code = fs.readFileSync(path, 'utf-8');
    vm.runInThisContext(code, global);
}

// Stub enough things to ignore UI pieces

global.window = {};
global.jQuery = {fn : {}};

include("profile-data.js");
include("shake.js", "test();");
test();
<commit_msg>Fix up the HTML test<commit_after>// RUN TEST USING:
// pushd ts && tsc && popd && node test.js

var fs = require("fs");
var vm = require("vm");

function include(path) {
    var code = fs.readFileSync(path, 'utf-8');
    vm.runInThisContext(code, global);
}

// Stub enough things to ignore UI pieces

global.window = {};
global.jQuery = {fn : {}};

include("data/profile-data.js");
include("shake.js");
test();
<|endoftext|>


<commit_before>'use strict';

var socketio = require('socket.io');
var Proto = require('uberproto');
var debug = require('debug')('feathers:primus');
var commons = require('feathers-commons').socket;

module.exports = function (config) {
  return function () {
    var app = this;

    app.enable('feathers socketio');

    // Monkey patch app.setup(server)
    Proto.mixin({
      service: commons.service,

      setup: function (server) {
        if (this.disabled('feathers socketio')) {
          return this._super.apply(this, arguments);
        }

        var io = this.io = socketio.listen(server);

        if (typeof config === 'function') {
          debug('Calling SocketIO configuration function');
          config.call(this, io);
        }

        var result = this._super.apply(this, arguments);

        debug('Setting up SocketIO');

        commons.setup.call(this, {
          method: 'emit',
          connection: function() {
            return io.sockets;
          },
          clients: function() {
            return io.sockets.sockets;
          },
          params: function(socket) {
            return socket.feathers;
          }
        });

        return result;
      }
    }, app);
  };
};
<commit_msg>Debug should be for socket.io instead of primus<commit_after>'use strict';

var socketio = require('socket.io');
var Proto = require('uberproto');
var debug = require('debug')('feathers:socket.io');
var commons = require('feathers-commons').socket;

module.exports = function (config) {
  return function () {
    var app = this;

    app.enable('feathers socketio');

    // Monkey patch app.setup(server)
    Proto.mixin({
      service: commons.service,

      setup: function (server) {
        if (this.disabled('feathers socketio')) {
          return this._super.apply(this, arguments);
        }

        var io = this.io = socketio.listen(server);

        if (typeof config === 'function') {
          debug('Calling SocketIO configuration function');
          config.call(this, io);
        }

        var result = this._super.apply(this, arguments);

        debug('Setting up SocketIO');

        commons.setup.call(this, {
          method: 'emit',
          connection: function() {
            return io.sockets;
          },
          clients: function() {
            return io.sockets.sockets;
          },
          params: function(socket) {
            return socket.feathers;
          }
        });

        return result;
      }
    }, app);
  };
};
<|endoftext|>


<commit_before>import Ember from 'ember';
import HasFieldStatus from 'ember-uni-form/mixins/has-field-status';
import { module, test } from 'qunit';

module('mixin:has-field-status');

test('it works', function (assert) {
  assert.ok(Ember.Object.extend(HasFieldStatus).create());
});
<commit_msg>bump code coverage a bit<commit_after>import Ember from 'ember';
import HasFieldStatus from 'ember-uni-form/mixins/has-field-status';
import { module, test } from 'qunit';

module('mixin:has-field-status');

test('it works', function (assert) {
  assert.ok(Ember.Object.extend(HasFieldStatus).create());
});

test('it should set focus on focusIn and reset it on focusOut', function (assert) {
  var subject = Ember.Object.extend(HasFieldStatus).create();
  subject.focusIn();
  assert.equal(subject.get('focus'), true);
  subject.focusOut();
  assert.equal(subject.get('focus'), false);
});
<|endoftext|>


<commit_before>(function () {
  'use strict';

  angular
    .module('articles')
    .controller('ArticlesController', ArticlesController);

  ArticlesController.$inject = ['$scope', '$state', 'articleResolve', '$window', 'Authentication'];

  function ArticlesController($scope, $state, article, $window, Authentication) {
    var vm = this;

    vm.article = article;
    vm.authentication = Authentication;
    vm.error = null;
    vm.form = {};
    vm.remove = remove;
    vm.save = save;

    // Remove existing Article
    function remove() {
      if ($window.confirm('Are you sure you want to delete?')) {
        vm.article.$remove($state.go('articles.list'));
      }
    }

    // Save Article
    function save(isValid) {
      if (!isValid) {
        $scope.$broadcast('show-errors-check-validity', 'vm.form.articleForm');
        return false;
      }

      // TODO: move create/update logic to service
      if (vm.article._id) {
        vm.article.$update(successCallback, errorCallback);
      } else {
        vm.article.$save(successCallback, errorCallback);
      }

      function successCallback(res) {
        $state.go('articles.view', {
          articleId: res._id
        });
      }

      function errorCallback(res) {
        vm.error = res.data.message;
      }
    }
  }
}());
<commit_msg>ar.cl.co<commit_after>(function() {
  'use strict';
  ///////////////////////////////////////////
  angular
    .module('articles')
    .controller('ArticlesController', ArticlesController);

  ArticlesController.$inject = ['$scope', '$state', 'articleResolve',
    '$window', 'Authentication'
  ];

  function ArticlesController($scope, $state, article, $window,
    Authentication) {
    var vm = this;

    vm.article = article;
    vm.authentication = Authentication;
    vm.error = null;
    vm.form = {};
    vm.remove = remove;
    vm.save = save;

    // Remove existing Article
    function remove() {
      if ($window.confirm('Are you sure you want to delete?')) {
        vm.article.$remove($state.go('articles.list'));
      }
    }

    // Save Article
    function save(isValid) {
      if (!isValid) {
        $scope.$broadcast('show-errors-check-validity', 'vm.form.articleForm');
        return false;
      }

      // TODO: move create/update logic to service
      if (vm.article._id) {
        vm.article.$update(successCallback, errorCallback);
      } else {
        vm.article.$save(successCallback, errorCallback);
      }

      function successCallback(res) {
        $state.go('articles.view', {
          articleId: res._id
        });
      }

      function errorCallback(res) {
        vm.error = res.data.message;
      }
    }
  }
}());
<|endoftext|>


<commit_before>var $ = require('jquery');
var createVis = require('../../../../src/api/create-vis');
var scenarios = require('./scenarios');

describe('create-vis-new:', function () {
  beforeEach(function () {
    this.container = $('
').css('height', '200px');
    this.containerId = this.container[0].id;
    $('body').append(this.container);
  });

  afterEach(function () {
    this.container.remove();
  });

  describe('Default Options', function () {
    it('should get the map center from the visJson', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.map.get('center')).toEqual(visJson.center);
    });
    it('should get the title from the visJson', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.get('title')).toEqual(visJson.title);
    });
    it('should get the description from the visJson', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.get('description')).toEqual(visJson.description);
    });
    it('should initialize the right protocol (https:false)', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.get('https')).toEqual(false);
    });
    it('should not have interactive features by default', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.get('interactiveFeatures')).toEqual(false);
    });
    it('should display the "loader" overlay by default [loaderControl, tiles_loader]', function () {
      // loaderControl and tiles_loader appear to do the same.
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.overlaysCollection.findWhere({ type: 'loader' })).toBeDefined();
    });
    it('should display the "logo" by default', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.overlaysCollection.findWhere({ type: 'logo' })).toBeDefined();
    });
    it('should not display empty infowindow fields by default', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.get('showEmptyInfowindowFields')).toEqual(false);
    });
    it('should have legends', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.settings.get('showLegends')).toEqual(true);
    });
    it('should show layer selector', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.settings.get('showLayerSelector')).toEqual(true);
      expect(visModel.settings.get('layerSelectorEnabled')).toEqual(true);
    });
    it('should allow scrollwheel by default', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.map.get('scrollwheel')).toEqual(true);
    });
    it('should have "infowindow" enabled by default', function () {
      pending('It seems that this option is no longer being used');
    });
    it('should have "tooltip" by default', function () {
      pending('It seems that this option  is no longer being used');
    });
  });

  describe('VisModel.map', function () {
    it('should have the right title', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.map.get('title')).toEqual(visJson.title);
    });
    it('should have the right description', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.map.get('description')).toEqual(visJson.description);
    });
    it('should have the right bounds', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.map.get('view_bounds_sw')).toEqual(visJson.bounds[0]);
      expect(visModel.map.get('view_bounds_ne')).toEqual(visJson.bounds[1]);
    });
    it('should have the right zoom', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.map.get('zoom')).toEqual(visJson.zoom);
    });
    it('should have the right scrollwheel', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.map.get('scrollwheel')).toEqual(visJson.options.scrollwheel);
    });
    it('should have the right drag', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.map.get('drag')).toEqual(true);
    });
    it('should have the right provider', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.map.get('provider')).toEqual('leaflet');
    });
    it('should have the right feature interactivity', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.map.get('isFeatureInteractivityEnabled')).toEqual(false);
    });
    it('should have the right render mode', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.map.get('renderMode')).toEqual(visJson.vector ? 'vector' : 'raster');
    });
  });

  describe('VisModel._windshaftMap', function () {
    it('should have the right statTag', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel._windshaftMap.get('statTag')).toEqual(visJson.datasource.stat_tag);
    });
    it('should have the _analysisCollection linked', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel._windshaftMap._analysisCollection).toEqual(visModel._analysisCollection);
    });
    it('should have the analysisCollection linked', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel._windshaftMap._analysisCollection).toEqual(visModel._analysisCollection);
    });
    it('should have the dataviewsCollection linked', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel._windshaftMap._dataviewsCollection).toEqual(visModel._dataviewsCollection);
    });
    it('should have the layersCollection linked', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel._windshaftMap._layersCollection).toEqual(visModel._layersCollection);
    });
    describe('.windshaftSettings', function () {
      it('should have the right urlTemplate', function () {
        var visJson = scenarios.load(0);
        var visModel = createVis(this.containerId, visJson);
        expect(visModel._windshaftMap._windshaftSettings.urlTemplate).toEqual(visJson.datasource.maps_api_template);
      });
      it('should have the right userName', function () {
        var visJson = scenarios.load(0);
        var visModel = createVis(this.containerId, visJson);
        expect(visModel._windshaftMap._windshaftSettings.userName).toEqual(visJson.datasource.user_name);
      });
      it('should have the right statTag', function () {
        var visJson = scenarios.load(0);
        var visModel = createVis(this.containerId, visJson);
        expect(visModel._windshaftMap._windshaftSettings.statTag).toEqual(visJson.datasource.stat_tag);
      });
      it('should not have apikey', function () {
        var visJson = scenarios.load(0);
        var visModel = createVis(this.containerId, visJson);
        expect(visModel._windshaftMap._windshaftSettings.apikey).toBeUndefined();
      });
      it('should not have authToken', function () {
        var visJson = scenarios.load(0);
        var visModel = createVis(this.containerId, visJson);
        expect(visModel._windshaftMap._windshaftSettings.authToken).toBeUndefined();
      });
    });
    describe('.client', function () {
      it('should have the right url', function () {
        var visJson = scenarios.load(0);
        var visModel = createVis(this.containerId, visJson);
        var expectedClientUrl = visJson.datasource.maps_api_template.replace(/{user}/, visJson.datasource.user_name);
        expect(visModel._windshaftMap.client.url).toEqual(expectedClientUrl);
      });
      it('should have the right get endpoint', function () {
        var visJson = scenarios.load(0);
        var visModel = createVis(this.containerId, visJson);
        var expectedGetEndPoint = 'api/v1/map/named/' + visJson.datasource.template_name + '/jsonp';
        expect(visModel._windshaftMap.client.endpoints.get).toEqual(expectedGetEndPoint);
      });
      it('should have the right post endpoint', function () {
        var visJson = scenarios.load(0);
        var visModel = createVis(this.containerId, visJson);
        var expectedGetEndPoint = 'api/v1/map/named/' + visJson.datasource.template_name;
        expect(visModel._windshaftMap.client.endpoints.post).toEqual(expectedGetEndPoint);
      });
    });
    describe('.modelUpdater', function () {
      it('should have the visModel linked', function () {
        var visJson = scenarios.load(0);
        var visModel = createVis(this.containerId, visJson);
        expect(visModel._windshaftMap._modelUpdater._visModel).toEqual(visModel);
      });
      it('should have the mapModel linked', function () {
        var visJson = scenarios.load(0);
        var visModel = createVis(this.containerId, visJson);
        expect(visModel._windshaftMap._modelUpdater._mapModel).toEqual(visModel.map);
      });
      it('should have the layerGroupModel linked', function () {
        var visJson = scenarios.load(0);
        var visModel = createVis(this.containerId, visJson);
        expect(visModel._windshaftMap._modelUpdater._layerGroupModel).toEqual(visModel.layerGroupModel);
      });
      it('should have the dataviewsCollection linked', function () {
        var visJson = scenarios.load(0);
        var visModel = createVis(this.containerId, visJson);
        expect(visModel._windshaftMap._modelUpdater._dataviewsCollection).toEqual(visModel._dataviewsCollection);
      });
      it('should have the layersCollection linked', function () {
        var visJson = scenarios.load(0);
        var visModel = createVis(this.containerId, visJson);
        expect(visModel._windshaftMap._modelUpdater._layersCollection).toEqual(visModel._layersCollection);
      });
      it('should have the analysisCollection linked', function () {
        var visJson = scenarios.load(0);
        var visModel = createVis(this.containerId, visJson);
        expect(visModel._windshaftMap._modelUpdater._analysisCollection).toEqual(visModel._analysisCollection);
      });
    });
  });

  xdescribe('VisModel.overlays', function () {
    it('should set the right map center', function () {});
  });

  xdescribe('VisModel.dataviews', function () {
    it('should set the right map center', function () {});
  });

  xdescribe('VisModel.analysis', function () {
    it('should set the right map center', function () {});
  });
});
<commit_msg>Add overlayCollection tests<commit_after>var $ = require('jquery');
var createVis = require('../../../../src/api/create-vis');
var scenarios = require('./scenarios');

describe('create-vis-new:', function () {
  beforeEach(function () {
    this.container = $('
').css('height', '200px');
    this.containerId = this.container[0].id;
    $('body').append(this.container);
  });

  afterEach(function () {
    this.container.remove();
  });

  describe('Default Options', function () {
    it('should get the map center from the visJson', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.map.get('center')).toEqual(visJson.center);
    });
    it('should get the title from the visJson', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.get('title')).toEqual(visJson.title);
    });
    it('should get the description from the visJson', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.get('description')).toEqual(visJson.description);
    });
    it('should initialize the right protocol (https:false)', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.get('https')).toEqual(false);
    });
    it('should not have interactive features by default', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.get('interactiveFeatures')).toEqual(false);
    });
    it('should display the "loader" overlay by default [loaderControl, tiles_loader]', function () {
      // loaderControl and tiles_loader appear to do the same.
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.overlaysCollection.findWhere({ type: 'loader' })).toBeDefined();
    });
    it('should display the "logo" by default', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.overlaysCollection.findWhere({ type: 'logo' })).toBeDefined();
    });
    it('should not display empty infowindow fields by default', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.get('showEmptyInfowindowFields')).toEqual(false);
    });
    it('should have legends', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.settings.get('showLegends')).toEqual(true);
    });
    it('should show layer selector', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.settings.get('showLayerSelector')).toEqual(true);
      expect(visModel.settings.get('layerSelectorEnabled')).toEqual(true);
    });
    it('should allow scrollwheel by default', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.map.get('scrollwheel')).toEqual(true);
    });
    it('should have "infowindow" enabled by default', function () {
      pending('It seems that this option is no longer being used');
    });
    it('should have "tooltip" by default', function () {
      pending('It seems that this option  is no longer being used');
    });
  });

  describe('VisModel.map', function () {
    it('should have the right title', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.map.get('title')).toEqual(visJson.title);
    });
    it('should have the right description', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.map.get('description')).toEqual(visJson.description);
    });
    it('should have the right bounds', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.map.get('view_bounds_sw')).toEqual(visJson.bounds[0]);
      expect(visModel.map.get('view_bounds_ne')).toEqual(visJson.bounds[1]);
    });
    it('should have the right zoom', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.map.get('zoom')).toEqual(visJson.zoom);
    });
    it('should have the right scrollwheel', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.map.get('scrollwheel')).toEqual(visJson.options.scrollwheel);
    });
    it('should have the right drag', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.map.get('drag')).toEqual(true);
    });
    it('should have the right provider', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.map.get('provider')).toEqual('leaflet');
    });
    it('should have the right feature interactivity', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.map.get('isFeatureInteractivityEnabled')).toEqual(false);
    });
    it('should have the right render mode', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.map.get('renderMode')).toEqual(visJson.vector ? 'vector' : 'raster');
    });
  });

  describe('VisModel._windshaftMap', function () {
    it('should have the right statTag', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel._windshaftMap.get('statTag')).toEqual(visJson.datasource.stat_tag);
    });
    it('should have the _analysisCollection linked', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel._windshaftMap._analysisCollection).toEqual(visModel._analysisCollection);
    });
    it('should have the analysisCollection linked', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel._windshaftMap._analysisCollection).toEqual(visModel._analysisCollection);
    });
    it('should have the dataviewsCollection linked', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel._windshaftMap._dataviewsCollection).toEqual(visModel._dataviewsCollection);
    });
    it('should have the layersCollection linked', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel._windshaftMap._layersCollection).toEqual(visModel._layersCollection);
    });
    describe('.windshaftSettings', function () {
      it('should have the right urlTemplate', function () {
        var visJson = scenarios.load(0);
        var visModel = createVis(this.containerId, visJson);
        expect(visModel._windshaftMap._windshaftSettings.urlTemplate).toEqual(visJson.datasource.maps_api_template);
      });
      it('should have the right userName', function () {
        var visJson = scenarios.load(0);
        var visModel = createVis(this.containerId, visJson);
        expect(visModel._windshaftMap._windshaftSettings.userName).toEqual(visJson.datasource.user_name);
      });
      it('should have the right statTag', function () {
        var visJson = scenarios.load(0);
        var visModel = createVis(this.containerId, visJson);
        expect(visModel._windshaftMap._windshaftSettings.statTag).toEqual(visJson.datasource.stat_tag);
      });
      it('should not have apikey', function () {
        var visJson = scenarios.load(0);
        var visModel = createVis(this.containerId, visJson);
        expect(visModel._windshaftMap._windshaftSettings.apikey).toBeUndefined();
      });
      it('should not have authToken', function () {
        var visJson = scenarios.load(0);
        var visModel = createVis(this.containerId, visJson);
        expect(visModel._windshaftMap._windshaftSettings.authToken).toBeUndefined();
      });
    });
    describe('.client', function () {
      it('should have the right url', function () {
        var visJson = scenarios.load(0);
        var visModel = createVis(this.containerId, visJson);
        var expectedClientUrl = visJson.datasource.maps_api_template.replace(/{user}/, visJson.datasource.user_name);
        expect(visModel._windshaftMap.client.url).toEqual(expectedClientUrl);
      });
      it('should have the right get endpoint', function () {
        var visJson = scenarios.load(0);
        var visModel = createVis(this.containerId, visJson);
        var expectedGetEndPoint = 'api/v1/map/named/' + visJson.datasource.template_name + '/jsonp';
        expect(visModel._windshaftMap.client.endpoints.get).toEqual(expectedGetEndPoint);
      });
      it('should have the right post endpoint', function () {
        var visJson = scenarios.load(0);
        var visModel = createVis(this.containerId, visJson);
        var expectedGetEndPoint = 'api/v1/map/named/' + visJson.datasource.template_name;
        expect(visModel._windshaftMap.client.endpoints.post).toEqual(expectedGetEndPoint);
      });
    });
    describe('.modelUpdater', function () {
      it('should have the visModel linked', function () {
        var visJson = scenarios.load(0);
        var visModel = createVis(this.containerId, visJson);
        expect(visModel._windshaftMap._modelUpdater._visModel).toEqual(visModel);
      });
      it('should have the mapModel linked', function () {
        var visJson = scenarios.load(0);
        var visModel = createVis(this.containerId, visJson);
        expect(visModel._windshaftMap._modelUpdater._mapModel).toEqual(visModel.map);
      });
      it('should have the layerGroupModel linked', function () {
        var visJson = scenarios.load(0);
        var visModel = createVis(this.containerId, visJson);
        expect(visModel._windshaftMap._modelUpdater._layerGroupModel).toEqual(visModel.layerGroupModel);
      });
      it('should have the dataviewsCollection linked', function () {
        var visJson = scenarios.load(0);
        var visModel = createVis(this.containerId, visJson);
        expect(visModel._windshaftMap._modelUpdater._dataviewsCollection).toEqual(visModel._dataviewsCollection);
      });
      it('should have the layersCollection linked', function () {
        var visJson = scenarios.load(0);
        var visModel = createVis(this.containerId, visJson);
        expect(visModel._windshaftMap._modelUpdater._layersCollection).toEqual(visModel._layersCollection);
      });
      it('should have the analysisCollection linked', function () {
        var visJson = scenarios.load(0);
        var visModel = createVis(this.containerId, visJson);
        expect(visModel._windshaftMap._modelUpdater._analysisCollection).toEqual(visModel._analysisCollection);
      });
    });
  });

  describe('VisModel.overlays', function () {
    it('should have a share overlay', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      // TODO: Review if this overlay is still supported!
      expect(visModel.overlaysCollection.findWhere({ type: 'share' })).toBeDefined();
    });
    it('should have a search overlay', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.overlaysCollection.findWhere({ type: 'search' })).toBeDefined();
    });
    it('should have a zoom overlay', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.overlaysCollection.findWhere({ type: 'zoom' })).toBeDefined();
    });
    it('should have a loader overlay', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.overlaysCollection.findWhere({ type: 'loader' })).toBeDefined();
    });
    it('should have a logo overlay', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.overlaysCollection.findWhere({ type: 'logo' })).toBeDefined();
    });
    it('should have a attribution overlay', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.overlaysCollection.findWhere({ type: 'attribution' })).toBeDefined();
    });
  });

  xdescribe('VisModel.dataviews', function () {
    it('should set the right map center', function () {

    });
  });

  xdescribe('VisModel.analysis', function () {
    it('should set the right map center', function () { });
  });
});
<|endoftext|>


<commit_before>'use strict';

(function () {
  // Articles Controller Spec
  describe('Messages Controller Tests', function () {
    // Initialize global variables
    var MessagesController,
      scope,
      $httpBackend,
      $stateParams,
      $location,
      Authentication,
      Messages,
      mockMessage;

    beforeAll(function() {
      angular.element(document.querySelector('head')).append('<base href="/">');
    });

    // The $resource service augments the response object with methods for updating and deleting the resource.
    // If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
    // the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
    // When the toEqualData matcher compares two objects, it takes only object properties into
    // account and ignores methods.
    beforeEach(function () {
      jasmine.addMatchers({
        toEqualData: function (util, customEqualityTesters) {
          return {
            compare: function (actual, expected) {
              return {
                pass: angular.equals(actual, expected)
              };
            }
          };
        }
      });
    });

    // Then we can start by loading the main application module
    beforeEach(module(ApplicationConfiguration.applicationModuleName));

    // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
    // This allows us to inject a service but then attach it to a variable
    // with the same name as the service.
    beforeEach(inject(function ($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_, _Authentication_, _Messages_) {
      // Set a new global scope
      scope = $rootScope.$new();

      // Point global variables to injected services
      $stateParams = _$stateParams_;
      $httpBackend = _$httpBackend_;
      $location = _$location_;
      Authentication = _Authentication_;
      Messages = _Messages_;

      // create mock article
      mockMessage = new Messages.lookup({
        _id: '525a8422f6d0f87f0e407a33',
        sender: '525a8422f6d0f87f0e407a55',
        content: 'Hello world!'
      });

      // Mock logged in user
      Authentication.user = {
        roles: ['student']
      };

      // Initialize the Messages controller.
      MessagesController = $controller('MessagesController', {
        $scope: scope
      });
    }));

    it('$scope.findOne() should create an array with one message object fetched from XHR', inject(function (Messages) {
      // Set the URL parameter
      $stateParams.messageId = mockMessage._id;

      // Set GET response
      $httpBackend.expectGET('/api/messages').respond(mockMessage);

      // Run controller functionality
      scope.find();
      $httpBackend.flush();

      // Test scope value
      expect(scope.showMessages).toEqualData(mockMessage);
    }));

    it('$scope.formatDate() should create a date object', inject(function (Messages) {

      var date = '29/10/2010';
      var expectedDate = new Date(date);
      // Run controller functionality
      var result = scope.formatDate(date);

      // Test result value
      expect(result).toEqualData(expectedDate);

    }));

    it('$scope.removeConvo() should delete a message object', inject(function (Messages) {

      scope.messages = mockMessage;
      // Set the URL parameter
      $httpBackend.expectPOST('/api/messages/'+mockMessage._id).respond(204);
      expect(scope.messages.length);

      scope.removeConvo(mockMessage);
      $httpBackend.flush();
    }));

    describe('$scope.create()', function () {
      var sampleMessagePostData;
      var convoId = '525a8422f6d0f87f0e407a33';

      beforeEach(function () {
        // Create a sample messages object
        sampleMessagePostData = new Messages.lookup({
          content: 'I love JS!',
          conversationId: '525a8422f6d0f87f0e407a33'
        });

        // Fixture mock form input values
        scope.content = 'I love JS!';

        spyOn($location, 'path');
      });

      it('should send a POST request with the form input values and then locate to new object URL', inject(function (Messages) {

        // Set POST response
        $httpBackend.expectPOST('api/messages', sampleMessagePostData).respond(mockMessage);

        // Set GET response
        $httpBackend.expectGET('/api/messages/'+mockMessage._id).respond(mockMessage);

        // Run controller functionality
        scope.create(convoId);
        $httpBackend.flush();

        // Test form inputs are reset
        expect(scope.content).toEqual('');
      }));

      it('should set scope.error if save error', function () {
        var errorMessage = 'this is an error message';
        $httpBackend.expectPOST('api/messages', sampleMessagePostData).respond(400, {
          message: errorMessage
        });

        scope.create(convoId);
        $httpBackend.flush();

        expect(scope.error).toBe(errorMessage);
      });
    });

  });
}());
<commit_msg>messages tests<commit_after>'use strict';

(function () {
  // Messages Controller Spec
  describe('Messages Controller Tests', function () {
    // Initialize global variables
    var MessagesController,
      scope,
      $httpBackend,
      $stateParams,
      $location,
      Authentication,
      Messages,
      mockMessage;

    beforeAll(function() {
      angular.element(document.querySelector('head')).append('<base href="/">');
    });

    // The $resource service augments the response object with methods for updating and deleting the resource.
    // If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
    // the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
    // When the toEqualData matcher compares two objects, it takes only object properties into
    // account and ignores methods.
    beforeEach(function () {
      jasmine.addMatchers({
        toEqualData: function (util, customEqualityTesters) {
          return {
            compare: function (actual, expected) {
              return {
                pass: angular.equals(actual, expected)
              };
            }
          };
        }
      });
    });

    // Then we can start by loading the main application module
    beforeEach(module(ApplicationConfiguration.applicationModuleName));

    // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
    // This allows us to inject a service but then attach it to a variable
    // with the same name as the service.
    beforeEach(inject(function ($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_, _Authentication_, _Messages_) {
      // Set a new global scope
      scope = $rootScope.$new();

      // Point global variables to injected services
      $stateParams = _$stateParams_;
      $httpBackend = _$httpBackend_;
      $location = _$location_;
      Authentication = _Authentication_;
      Messages = _Messages_;

      // create mock message
      mockMessage = new Messages.lookup({
        _id: '525a8422f6d0f87f0e407a33',
        sender: '525a8422f6d0f87f0e407a55',
        content: 'Hello world!'
      });

      // Mock logged in user
      Authentication.user = {
        roles: ['student']
      };

      // Initialize the Messages controller.
      MessagesController = $controller('MessagesController', {
        $scope: scope
      });
    }));

    it('$scope.findOne() should create an array with one message object fetched from XHR', inject(function (Messages) {
      // Set the URL parameter
      $stateParams.messageId = mockMessage._id;

      // Set GET response
      $httpBackend.expectGET('/api/messages').respond(mockMessage);

      // Run controller functionality
      scope.find();
      $httpBackend.flush();

      // Test scope value
      expect(scope.showMessages).toEqualData(mockMessage);
    }));

    it('$scope.formatDate() should create a date object', inject(function (Messages) {

      var date = '29/10/2010';
      var expectedDate = new Date(date);
      // Run controller functionality
      var result = scope.formatDate(date);

      // Test result value
      expect(result).toEqualData(expectedDate);

    }));

    it('$scope.removeConvo() should delete a message object', inject(function (Messages) {

      scope.messages = mockMessage;
      // Set the URL parameter
      $httpBackend.expectPOST('/api/messages/'+mockMessage._id).respond(204);
      expect(scope.messages.length);

      scope.removeConvo(mockMessage);
      $httpBackend.flush();
    }));

    describe('$scope.create()', function () {
      var sampleMessagePostData;
      var convoId = '525a8422f6d0f87f0e407a33';

      beforeEach(function () {
        // Create a sample messages object
        sampleMessagePostData = new Messages.lookup({
          content: 'I love JS!',
          conversationId: '525a8422f6d0f87f0e407a33'
        });

        // Fixture mock form input values
        scope.content = 'I love JS!';

        spyOn($location, 'path');
      });

      it('should send a POST request with the form input values and then locate to new object URL', inject(function (Messages) {

        // Set POST response
        $httpBackend.expectPOST('api/messages', sampleMessagePostData).respond(mockMessage);

        // Set GET response
        $httpBackend.expectGET('/api/messages/'+mockMessage._id).respond(mockMessage);

        // Run controller functionality
        scope.create(convoId);
        $httpBackend.flush();

        // Test form inputs are reset
        expect(scope.content).toEqual('');
      }));

      it('should set scope.error if save error', function () {
        var errorMessage = 'this is an error message';
        $httpBackend.expectPOST('api/messages', sampleMessagePostData).respond(400, {
          message: errorMessage
        });

        scope.create(convoId);
        $httpBackend.flush();

        expect(scope.error).toBe(errorMessage);
      });

      it('Should include CRUD methods', function() {
        expect(scope.find).toBeDefined();
        expect(scope.create).toBeDefined();
        expect(scope.removeConvo).toBeDefined();
        expect(scope.findMessages).toBeDefined();
        expect(scope.formatDate).toBeDefined();
      });
    });

  });
}());
<|endoftext|>


<commit_before>/* jshint expr:true */

define(['require', 'intern/chai!', 'intern/dojo/node!sinon-chai', 'intern/dojo/node!sinon'], function (require, chai, sinonChai, sinon) {
  var registerSuite = require('intern!object'),
      assert        = require('intern/chai!assert'),
      fs            = require('intern/dojo/node!fs'),
      polish        = require('intern/dojo/node!../../lib/polish');

  chai.use(sinonChai);

  registerSuite(function() {
    var consoleLogStub;

    return {
      name: 'polish-error-reporter',

      beforeEach: function() {
        consoleLogStub = sinon.stub(console, 'log');
      },
      afterEach: function() {
        consoleLogStub.restore();
      },

      'test that it does not report if there are no errors': function() {
        var deferred = this.async(3000),
            results;

        fs.readFile('./tests/test_helpers/no-errors.css', deferred.callback(function(error, stylesheet) {
          if (error) {
            throw error;
          }

          results = polish(stylesheet.toString('utf8'), './tests/test_helpers/no-errors.css', [ { module: 'polish-no-styling-ids', severity: 2 }, { module: 'polish-no-styling-elements', severity: 2 } ] );

          polish.reporter('./tests/test_helpers/no-errors.css', results.errors, results.warnings);

          chai.expect(consoleLogStub).to.not.be.called;
        }));
      },
      'test that it reports an error': function() {
        var deferred = this.async(3000),
            results;

        fs.readFile('./tests/test_helpers/scss.scss', deferred.callback(function(error, stylesheet) {
          if (error) {
            throw error;
          }

          results = polish(stylesheet.toString('utf8'), './tests/test_helpers/scss.scss', [ { module: 'polish-no-styling-ids', severity: 2 } ]);

          polish.reporter('./tests/test_helpers/scss.scss', results.errors, results.warnings);

          chai.expect(consoleLogStub).to.be.calledOnce;
          /* should report the filename */
          chai.expect(consoleLogStub).and.calledWithMatch(results.filePath);
          /* should report the line number */
          chai.expect(consoleLogStub).to.be.calledWithMatch(results.errors[0].error.node.start.line + ':' + results.errors[0].error.node.start.column);
          /* should report the failed node as a string */
          chai.expect(consoleLogStub).to.be.calledWithMatch('#no-styling-ids');
          /* should report the error message */
          chai.expect(consoleLogStub).to.be.calledWithMatch(results.errors[0].plugin.message);
        }));
      },
      'test that it reports multiple errors grouped under the filename': function() {
        var deferred = this.async(3000),
            results;

        fs.readFile('./tests/test_helpers/scss.scss', deferred.callback(function(error, stylesheet) {
          if (error) {
            throw error;
          }

          results = polish(stylesheet.toString('utf8'), './tests/test_helpers/scss.scss', [ { module: 'polish-no-styling-ids', severity: 2 }, { module: 'polish-no-styling-elements', severity: 2 } ]);

          polish.reporter('./tests/test_helpers/scss.scss', results.errors, results.warnings);

          chai.expect(consoleLogStub).to.be.calledOnce;
          /* should report the filename */
          chai.expect(consoleLogStub).to.be.calledWithMatch(results.filePath);
          /* should report the line number */
          chai.expect(consoleLogStub).to.be.calledWithMatch(results.errors[0].error.node.start.line + ':' + results.errors[0].error.node.start.column);
          chai.expect(consoleLogStub).to.be.calledWithMatch(results.errors[1].error.node.start.line + ':' + results.errors[1].error.node.start.column);
          /* should report the failed node as a string */
          chai.expect(consoleLogStub).to.be.calledWithMatch('#no-styling-ids');
          chai.expect(consoleLogStub).to.be.calledWithMatch('div');
          /* should report the error message */
          chai.expect(consoleLogStub).to.be.calledWithMatch(results.errors[0].plugin.message);
          chai.expect(consoleLogStub).to.be.calledWithMatch(results.errors[1].plugin.message);
        }));
      },
      'test that it reports both file-level and node-level errors': function() {
          var deferred = this.async(3000),
              results;

        fs.readFile('./tests/test_helpers/scss.scss', deferred.callback(function(error, stylesheet) {
          if (error) {
            throw error;
          }

          results = polish(stylesheet.toString('utf8'), './tests/test_helpers/scss.scss', [ { module: 'polish-no-styling-ids', severity: 2 }, { module: 'polish-no-styling-elements', severity: 2 }, { module: 'polish-match-stylesheet-names-to-rules', severity: 2 } ]);

          polish.reporter('./tests/test_helpers/scss.scss', results.errors, results.warnings);

          chai.expect(consoleLogStub).to.be.calledOnce;
          /* should report the filename */
          chai.expect(consoleLogStub).to.be.calledWithMatch(results.filePath);
          /* should report the line number */
          chai.expect(consoleLogStub).to.be.calledWithMatch(results.errors[0].error.node.start.line + ':' + results.errors[0].error.node.start.column);
          chai.expect(consoleLogStub).to.be.calledWithMatch(results.errors[1].error.node.start.line + ':' + results.errors[1].error.node.start.column);
          /* should report the failed node as a string */
          chai.expect(consoleLogStub).to.be.calledWithMatch('#no-styling-ids');
          chai.expect(consoleLogStub).to.be.calledWithMatch('div');
          chai.expect(consoleLogStub).to.be.calledWithMatch('File warning');
          /* should report the error message */
          chai.expect(consoleLogStub).to.be.calledWithMatch(results.errors[0].plugin.message);
          chai.expect(consoleLogStub).to.be.calledWithMatch(results.errors[1].plugin.message);
          chai.expect(consoleLogStub).to.be.calledWithMatch(results.errors[2].plugin.message({
            error : {
              errorName: 'failed_on_multiple',
              message: ''
            }
          }));
        }));
      }
    };
  });
});
<commit_msg>tests: Cover warnings in reporter as well as errors, test for excerpts of AST nodes that are too long to reasonably print<commit_after>/* jshint expr:true */

define(['require', 'intern/chai!', 'intern/dojo/node!sinon-chai', 'intern/dojo/node!sinon'], function (require, chai, sinonChai, sinon) {
  var registerSuite = require('intern!object'),
      assert        = require('intern/chai!assert'),
      fs            = require('intern/dojo/node!fs'),
      polish        = require('intern/dojo/node!../../lib/polish');

  chai.use(sinonChai);

  registerSuite(function() {
    var consoleLogStub;

    return {
      name: 'polish-error-reporter',

      beforeEach: function() {
        consoleLogStub = sinon.stub(console, 'log');
      },
      afterEach: function() {
        consoleLogStub.restore();
      },

      'test that it does not report if there are no errors': function() {
        var deferred = this.async(3000),
            results;

        fs.readFile('./tests/test_helpers/no-errors.css', deferred.callback(function(error, stylesheet) {
          if (error) {
            throw error;
          }

          results = polish(stylesheet.toString('utf8'), './tests/test_helpers/no-errors.css', [ { module: 'polish-no-styling-ids', severity: 2 }, { module: 'polish-no-styling-elements', severity: 2 } ] );

          polish.reporter('./tests/test_helpers/no-errors.css', results.errors, results.warnings);

          chai.expect(consoleLogStub).to.not.be.called;
        }));
      },
      'test that it reports errors and warnings': function() {
        var deferred = this.async(3000),
            results;

        fs.readFile('./tests/test_helpers/scss.scss', deferred.callback(function(error, stylesheet) {
          if (error) {
            throw error;
          }

          results = polish(stylesheet.toString('utf8'), './tests/test_helpers/scss.scss', [ { module: 'polish-no-styling-ids', severity: 2 }, { module: 'polish-no-styling-elements', severity: 1 }, { module: 'polish-match-stylesheet-names-to-rules', severity: 0 } ]);

          polish.reporter('./tests/test_helpers/scss.scss', results.errors, results.warnings);

          chai.expect(consoleLogStub).to.be.calledOnce;
          /* should report the filename */
          chai.expect(consoleLogStub).and.calledWithMatch(results.filePath);
          /* should report the line numbers */
          chai.expect(consoleLogStub).to.be.calledWithMatch(results.errors[0].error.node.start.line + ':' + results.errors[0].error.node.start.column);
          chai.expect(consoleLogStub).to.be.calledWithMatch(results.warnings[0].error.node.start.line + ':' + results.warnings[0].error.node.start.column);
          /* should report the failed node as a string */
          chai.expect(consoleLogStub).to.be.calledWithMatch('#no-styling-ids');
          chai.expect(consoleLogStub).to.be.calledWithMatch('div');
          /* should report the error message */
          chai.expect(consoleLogStub).to.be.calledWithMatch(results.errors[0].plugin.message);
          chai.expect(consoleLogStub).to.be.calledWithMatch(results.warnings[0].plugin.message);
          chai.expect(consoleLogStub).to.not.be.calledWithMatch('Do not use multiple top-level rules in a file.');
        }));
      },
      'test that it reports multiple errors grouped under the filename': function() {
        var deferred = this.async(3000),
            results;

        fs.readFile('./tests/test_helpers/scss.scss', deferred.callback(function(error, stylesheet) {
          if (error) {
            throw error;
          }

          results = polish(stylesheet.toString('utf8'), './tests/test_helpers/scss.scss', [ { module: 'polish-no-styling-ids', severity: 2 }, { module: 'polish-no-styling-elements', severity: 2 } ]);

          polish.reporter('./tests/test_helpers/scss.scss', results.errors, results.warnings);

          chai.expect(consoleLogStub).to.be.calledOnce;
          /* should report the filename */
          chai.expect(consoleLogStub).to.be.calledWithMatch(results.filePath);
          /* should report the line number */
          chai.expect(consoleLogStub).to.be.calledWithMatch(results.errors[0].error.node.start.line + ':' + results.errors[0].error.node.start.column);
          chai.expect(consoleLogStub).to.be.calledWithMatch(results.errors[1].error.node.start.line + ':' + results.errors[1].error.node.start.column);
          /* should report the failed node as a string */
          chai.expect(consoleLogStub).to.be.calledWithMatch('#no-styling-ids');
          chai.expect(consoleLogStub).to.be.calledWithMatch('div');
          /* should report the error message */
          chai.expect(consoleLogStub).to.be.calledWithMatch(results.errors[0].plugin.message);
          chai.expect(consoleLogStub).to.be.calledWithMatch(results.errors[1].plugin.message);
        }));
      },
      'test that it reports both file-level and node-level errors': function() {
          var deferred = this.async(3000),
              results;

        fs.readFile('./tests/test_helpers/scss.scss', deferred.callback(function(error, stylesheet) {
          if (error) {
            throw error;
          }

          results = polish(stylesheet.toString('utf8'), './tests/test_helpers/scss.scss', [ { module: 'polish-no-styling-ids', severity: 2 }, { module: 'polish-no-styling-elements', severity: 2 }, { module: 'polish-match-stylesheet-names-to-rules', severity: 1 } ]);

          polish.reporter('./tests/test_helpers/scss.scss', results.errors, results.warnings);

          chai.expect(consoleLogStub).to.be.calledOnce;
          /* should report the filename */
          chai.expect(consoleLogStub).to.be.calledWithMatch(results.filePath);
          /* should report the line number */
          chai.expect(consoleLogStub).to.be.calledWithMatch(results.errors[0].error.node.start.line + ':' + results.errors[0].error.node.start.column);
          chai.expect(consoleLogStub).to.be.calledWithMatch(results.errors[1].error.node.start.line + ':' + results.errors[1].error.node.start.column);
          /* should report the failed node as a string */
          chai.expect(consoleLogStub).to.be.calledWithMatch('#no-styling-ids');
          chai.expect(consoleLogStub).to.be.calledWithMatch('div');
          chai.expect(consoleLogStub).to.be.calledWithMatch('File warning');
          /* should report the error message */
          chai.expect(consoleLogStub).to.be.calledWithMatch(results.errors[0].plugin.message);
          chai.expect(consoleLogStub).to.be.calledWithMatch(results.errors[1].plugin.message);
          chai.expect(consoleLogStub).to.be.calledWithMatch(results.warnings[0].plugin.message({
            error : {
              errorName: 'failed_on_multiple',
              message: ''
            }
          }));
        }));
      },
      'test that excerpts that are too long are condensed': function() {
          var deferred = this.async(3000),
              results;

        fs.readFile('./tests/test_helpers/scss.scss', deferred.callback(function(error, stylesheet) {
          if (error) {
            throw error;
          }

          results = polish(stylesheet.toString('utf8'), './tests/test_helpers/scss.scss', [ { module: 'polish-no-styling-ids', severity: 2 }, { module: 'polish-no-styling-elements', severity: 2 }, { module: 'polish-match-stylesheet-names-to-rules', severity: 2 } ]);

          results.errors[0].error.node = {
            start : {
              line   : 1,
              column : 1
            },
            toString : function() {
              return '123456789012345678901234567890123456789012345678901234567890';
            }
          };

          polish.reporter('./tests/test_helpers/scss.scss', results.errors, results.warnings);

          chai.expect(consoleLogStub).to.be.calledWithMatch('123456789012345678901234567890...');
        }));
      }
    };
  });
});
<|endoftext|>


<commit_before>var debug = require('debug')('follower:network:bloglovin')
  , request = require('./request');

/**
 * Create a new Bloglovin instance.
 *
 * @param {Object} options (optional)
 */

function Bloglovin(options) {
    options = options || (options = {});
    this.request = options.request || request;
    if (options.cache) {
        options.cache.memoise(this);
    }
}

exports.Bloglovin = Bloglovin;

/**
 * Get the number of bloglovin followers a blog has.
 *
 * Example:
 *   bloglovin.followerCount('3668940', function (err, followers) {
 *       console.log(followers); // => 20580
 *   });
 *
 * @param {String} url
 * @param {String} callback
 */

Bloglovin.prototype.followerCount = function (url, callback) {
    url += '';
    if (url.indexOf('/') === -1) {
        url = 'http://www.bloglovin.com/blog/' + url;
    } else if (!/^http:\/\//.test(url)) {
        if (!/^www\./.test(url)) {
            url = 'www.' + url;
        }
        url = 'http://' + url;
    }
    this.request(url, function (err, response) {
        if (err) return callback(err);
        if (/<strong>([0-9 \r\t\n]+?)<\/strong>/.test(response.body)) {
            var followers = Number(RegExp.$1.replace(/ /g, ''));
            debug('%s following %s', followers, url);
            return callback(null, followers);
        }
        debug('Failed to get bloglovin follower count for %s', url);
        callback(new Error('Invalid response'));
    });
};

<commit_msg>Bloglovin follower count update<commit_after>var debug = require('debug')('follower:network:bloglovin')
  , request = require('./request');

/**
 * Create a new Bloglovin instance.
 *
 * @param {Object} options (optional)
 */

function Bloglovin(options) {
    options = options || (options = {});
    this.request = options.request || request;
    if (options.cache) {
        options.cache.memoise(this);
    }
}

exports.Bloglovin = Bloglovin;

/**
 * Get the number of bloglovin followers a blog has.
 *
 * Example:
 *   bloglovin.followerCount('3668940', function (err, followers) {
 *       console.log(followers); // => 20580
 *   });
 *
 * @param {String} url
 * @param {String} callback
 */

Bloglovin.prototype.followerCount = function (url, callback) {
    url += '';
    if (url.indexOf('/') === -1) {
        url = 'http://www.bloglovin.com/blog/' + url;
    } else if (!/^http:\/\//.test(url)) {
        if (!/^www\./.test(url)) {
            url = 'www.' + url;
        }
        url = 'http://' + url;
    }
    this.request(url, function (err, response) {
        if (err) return callback(err);
        if (/<strong class=.followers-count.>([0-9 \r\t\n]+?)<\/strong>/.test(response.body)) {
            var followers = Number(RegExp.$1.replace(/ /g, ''));
            debug('%s following %s', followers, url);
            return callback(null, followers);
        }
        debug('Failed to get bloglovin follower count for %s', url);
        callback(new Error('Invalid response'));
    });
};

<|endoftext|>