<commit_before>(function () {
  var dfm = require('./dfm');

  var items = [];
  var itemsMap = {};
  var base = '_yamlGeneratorOutput';
  var globalUid = 'global';
  var uidPrefix = '';
  var yamlMime = "### YamlMime:UniversalReference";
  var outputFileExt = ".yml";
  var jsdocConfigPath = '_jsdocConfTemp.json';
  var builtInTypes = ["array","arraybuffer","asyncfunction","atomics","boolean","dataview","date","error","evalerror","float32array","float64array","function","generator","generatorfunction","infinity","int16array","int32array","int8array","internalerror","intl","intl.collator","intl.datetimeformat","intl.numberformat","iterator","json","map","math","nan","number","object","parallelarray","promise","proxy","rangeerror","referenceerror","reflect","regexp","simd","simd.bool16x8","simd.bool32x4","simd.bool64x2","simd.bool8x16","simd.float32x4","simd.float64x2","simd.int16x8","simd.int32x4","simd.int8x16","simd.uint16x8","simd.uint32x4","simd.uint8x16","set","sharedarraybuffer","stopiteration","string","symbol","syntaxerror","typeerror","typedarray","urierror","uint16array","uint32array","uint8array","uint8clampedarray","weakmap","weakset", "undefined"]

  function addItem(item) {
    item.langs = ["js"];
    items.push(item);
    itemsMap[item.uid] = item;
  }

  function setSourceInfo(item, doclet) {
    var path = doclet.meta.path.replace(env.pwd + "\\", "") + "\\" + doclet.meta.filename;
    if (path.split("\\").length > 2) {
      path = path.split("\\").splice(2).join("\\");
    }
    item.source = {
      id: item.id,
      path: path,
      startLine: doclet.lineno,
      remote: {
        branch: "master",
        path: path,
        repo: "https://github.com/Azure/azure-sdk-for-node.git"
      }
    };
  }

  function handleClass(item, doclet) {
    item.type = "Class";
    item.summary = dfm.convertLinkToGfm(doclet.classdesc);
    // set syntax
    // item.syntax = {};
    // hmm... anything better? -- seems no need to add class syntax?
    // item.syntax.content = item.name;
    // add a constructor
    var ctor = {
      id: item.id + ".#ctor",
      uid: item.uid + ".#ctor",
      parent: item.uid,
      name: item.name,
      fullName: item.fullName + '.' + item.name,
      summary: dfm.convertLinkToGfm(doclet.description)
    };
    handleFunction(ctor, doclet);
    item.children = [ctor.uid];
    addItem(ctor);
  }

  function handleFunction(item, doclet) {
    item.type = doclet.kind === "function" ? "Function" : "Constructor";
    item.syntax = {};
    // set parameters
    if (doclet.params !== undefined) {
      item.syntax.parameters = doclet.params.map(function (p) {
        return {
          id: p.name,
          type: handleParameterType(p.type),
          description: dfm.convertLinkToGfm(p.description),
          optional: p.optional
        };
      });
    }
    // set name and fullName
    var params = [];
    (item.syntax.parameters || []).forEach(function (p) {
      if (p.id.indexOf(".") < 0) params.push(p.id);
    });
    item.name += "(" + params.join(", ") + ")";
    item.fullName += "(" + params.join(", ") + ")";
    // set return type
    if (doclet.returns != undefined) {
      item.syntax.return = {
        type: handleParameterType(doclet.returns[0].type),
        description: dfm.convertLinkToGfm(doclet.returns[0].description),
        optional: doclet.returns[0].optional
      };
    }
    // set syntax
    // which one is better:
    // 1. function method_name(arg1, arg2, ...);
    // 2. return_type function method_name(arg1, arg2)
    // 3. function method_name(arg1, arg2) -> return_type
    item.syntax.content = (item.type === "Function" ? "function " : "new ") + item.name;

    function handleParameterType(type) {
      if (!type) return undefined;
      return type.names.map(function (n) {
        if (builtInTypes.indexOf(n.toLowerCase()) == -1) {
          n = uidPrefix + n;
        }
        return n;
      });
    }
  }

  function handleMember(item, doclet) {
    item.type = "Member";
    // set type
    item.syntax = {};
    if (doclet.type != undefined) {
      item.syntax.return = {
        type: [doclet.type.names[0]]
      };
    }
    // set syntax
    item.syntax.content = item.name;
  }

  function serialize() {
    var serializer = require("js-yaml");
    var fs = require("fs");
    var classes = {};
    var fileMap = {};
    if (!fs.existsSync(base)) {
      fs.mkdirSync(base);
    }
    items.forEach(function (i) {
      switch (i.type) {
        case "Class":
          classes[i.uid] = {
            items: [i],
            referenceMap: {}
          };
          fileMap[i.uid] = i.uid;
          break;
        case "Constructor":
        case "Function":
        case "Member":
          var parentId = i.parent || globalUid;
          var parent = classes[parentId];
          if (parent === undefined) {
            console.log(parentId + " is not a class, ignored.");
            break;
          }
          parent.items.push(i);
          if (parentId === globalUid) {
            (parent.items[0].children = parent.items[0].children || []).push(i.uid);
          }
          fileMap[i.uid] = parentId;
          (i.syntax.parameters || []).forEach(function (p) {
            (p.type || []).forEach(function (t) {
              classes[parentId].referenceMap[t] = true;
            });
          });
          if (i.syntax.return) {
            (i.syntax.return.type || []).forEach(function (t) {
              classes[parentId].referenceMap[t] = true;
            })
          }
          break;
      }
    });

    var toc = [];
    for (var id in classes) {
      var c = classes[id];
      // build references
      c.references = [];
      for (var r in c.referenceMap) {
        var f = fileMap[r];
        if (f !== id) {
          c.references.push({
            uid: r,
            name: r.indexOf(".") == -1 ? r : r.substring(r.indexOf(".") + 1),
            fullName: r,
            isExternal: f === undefined
          });
        }
      }
      c.referenceMap = undefined;
      if (c.references.length == 0) {
        c.references = undefined;
      }

      // something wrong in js-yaml, workaround it by serialize and deserialize from JSON
      var c = JSON.parse(JSON.stringify(c));
      // replace \r, \n, space with dash
      var fileName = id.replace(/[ \n\r]/g, "-") + outputFileExt;
      if (fileName && fileName.split(".").length > 2) {
        fileName = fileName.split(".").splice(1).join(".");
      }
      fs.writeFileSync(base + '/' + fileName, yamlMime + '\n' + serializer.safeDump(c));
      console.log(fileName + " generated.");
      toc.push({
        uid: id,
        name: c.items[0].name
      });
    };
    toc.sort(function (a, b) {
      // sort classes alphabetically, but GLOBAL at last
      if (a.uid === globalUid) {
        return 1;
      }
      if (b.uid === globalUid) {
        return -1;
      }
      var nameA = a.name.toUpperCase();
      var nameB = b.name.toUpperCase();
      if (nameA < nameB) {
        return -1;
      }
      if (nameA > nameB) {
        return 1;
      }

      return 0;
    });

    fs.writeFileSync(base + "/toc.yml", serializer.safeDump(toc));
    console.log("toc.yml generated.");
  }

  var typeMap = {
    "member": handleMember,
    "function": handleFunction,
    "class": handleClass
  };

  exports.handlers = {
    newDoclet: function (e) {
      var doclet = e.doclet;
      // ignore anything whose parent is not a doclet
      // except it's a class made with help function
      if (doclet.memberof !== undefined && itemsMap[uidPrefix + doclet.memberof] === undefined && doclet.kind !== "class") {
        return;
      }
      // ignore unrecognized kind
      if (typeMap[doclet.kind] === undefined) {
        console.log("unrecognized kind: " + doclet.kind);
        return;
      }
      // ignore unexported global member
      if (doclet.memberof === undefined && doclet.kind != "class" && !(doclet.meta && doclet.meta.code && doclet.meta.code.name && doclet.meta.code.name.indexOf("exports") == 0)) {
        return;
      }
      // ignore inner function or member
      if (doclet.kind === "member" && doclet.scope === "inner") {
        return;
      }

      // ignore doclet without doucment
      if (doclet.undocumented === true) {
        return;
      }

      // ignore empty longname
      if (!doclet.longname) {
        return;
      }
      var parent = '';
      if (doclet.memberof === undefined && doclet.kind !== "class") {
        parent = "_global.";
      }
      // basic properties
      var item = {
        uid: uidPrefix + parent + doclet.longname,
        id: uidPrefix + parent + doclet.longname,
        parent: (doclet.memberof && doclet.kind !== "class") ? (uidPrefix + doclet.memberof) : undefined,
        name: doclet.name,
        summary: doclet.description ? dfm.convertLinkToGfm(doclet.description) : dfm.convertLinkToGfm(doclet.summary)
      };
      // set parent
      if (item.parent !== undefined) {
        var parent = itemsMap[item.parent];
        (parent.children = parent.children || []).push(item.uid);
      }
      // set full name
      item.fullName = (item.parent ? item.parent + "." : uidPrefix) + item.name;

      // set source info
      if (doclet.kind === "class") {
        setSourceInfo(item, doclet);
      }

      addItem(item);
      typeMap[doclet.kind](item, doclet);
    },
    parseBegin: function () {
      var fs = require('fs');
      var fse = require('fs-extra');
      var path = require('path');
      var config = fse.readJsonSync(jsdocConfigPath);

      // copy readme.md to index.md
      if (config.readme) {
        fse.copySync(config.readme, path.join(base, 'index.md'));
      }

      // parse package.json to use package name
      if (config.package) {
        var packageJson = fse.readJsonSync(config.package);
        if (packageJson && packageJson.name) {
          globalUid = packageJson.name + "." + globalUid;
          uidPrefix = packageJson.name + ".";
        }
      }
      items.push(
        {
          uid: globalUid,
          id: globalUid,
          name: "GLOBAL",
          fullName: "GLOBAL",
          type: "Class",
          summary: "global object",
          langs: ["js"]
        }
      )
    },
    parseComplete: function () {
      serialize();
      // no need to generate html, directly exit process
      process.exit(0);
    }
  };
})();
<commit_msg>fix an issue in reference<commit_after>(function () {
  var dfm = require('./dfm');

  var items = [];
  var itemsMap = {};
  var base = '_yamlGeneratorOutput';
  var globalUid = 'global';
  var uidPrefix = '';
  var yamlMime = "### YamlMime:UniversalReference";
  var outputFileExt = ".yml";
  var jsdocConfigPath = '_jsdocConfTemp.json';
  var builtInTypes = ["array","arraybuffer","asyncfunction","atomics","boolean","dataview","date","error","evalerror","float32array","float64array","function","generator","generatorfunction","infinity","int16array","int32array","int8array","internalerror","intl","intl.collator","intl.datetimeformat","intl.numberformat","iterator","json","map","math","nan","number","object","parallelarray","promise","proxy","rangeerror","referenceerror","reflect","regexp","simd","simd.bool16x8","simd.bool32x4","simd.bool64x2","simd.bool8x16","simd.float32x4","simd.float64x2","simd.int16x8","simd.int32x4","simd.int8x16","simd.uint16x8","simd.uint32x4","simd.uint8x16","set","sharedarraybuffer","stopiteration","string","symbol","syntaxerror","typeerror","typedarray","urierror","uint16array","uint32array","uint8array","uint8clampedarray","weakmap","weakset", "undefined"]

  function addItem(item) {
    item.langs = ["js"];
    items.push(item);
    itemsMap[item.uid] = item;
  }

  function setSourceInfo(item, doclet) {
    var path = doclet.meta.path.replace(env.pwd + "\\", "") + "\\" + doclet.meta.filename;
    if (path.split("\\").length > 2) {
      path = path.split("\\").splice(2).join("\\");
    }
    item.source = {
      id: item.id,
      path: path,
      startLine: doclet.lineno,
      remote: {
        branch: "master",
        path: path,
        repo: "https://github.com/Azure/azure-sdk-for-node.git"
      }
    };
  }

  function handleClass(item, doclet) {
    item.type = "Class";
    item.summary = dfm.convertLinkToGfm(doclet.classdesc);
    // set syntax
    // item.syntax = {};
    // hmm... anything better? -- seems no need to add class syntax?
    // item.syntax.content = item.name;
    // add a constructor
    var ctor = {
      id: item.id + ".#ctor",
      uid: item.uid + ".#ctor",
      parent: item.uid,
      name: item.name,
      fullName: item.fullName + '.' + item.name,
      summary: dfm.convertLinkToGfm(doclet.description)
    };
    handleFunction(ctor, doclet);
    item.children = [ctor.uid];
    addItem(ctor);
  }

  function handleFunction(item, doclet) {
    item.type = doclet.kind === "function" ? "Function" : "Constructor";
    item.syntax = {};
    // set parameters
    if (doclet.params !== undefined) {
      item.syntax.parameters = doclet.params.map(function (p) {
        return {
          id: p.name,
          type: handleParameterType(p.type),
          description: dfm.convertLinkToGfm(p.description),
          optional: p.optional
        };
      });
    }
    // set name and fullName
    var params = [];
    (item.syntax.parameters || []).forEach(function (p) {
      if (p.id.indexOf(".") < 0) params.push(p.id);
    });
    item.name += "(" + params.join(", ") + ")";
    item.fullName += "(" + params.join(", ") + ")";
    // set return type
    if (doclet.returns != undefined) {
      item.syntax.return = {
        type: handleParameterType(doclet.returns[0].type),
        description: dfm.convertLinkToGfm(doclet.returns[0].description),
        optional: doclet.returns[0].optional
      };
    }
    // set syntax
    // which one is better:
    // 1. function method_name(arg1, arg2, ...);
    // 2. return_type function method_name(arg1, arg2)
    // 3. function method_name(arg1, arg2) -> return_type
    item.syntax.content = (item.type === "Function" ? "function " : "new ") + item.name;

    function handleParameterType(type) {
      if (!type) return undefined;
      return type.names.map(function (n) {
        if (builtInTypes.indexOf(n.toLowerCase()) == -1) {
          n = uidPrefix + n;
        }
        return n;
      });
    }
  }

  function handleMember(item, doclet) {
    item.type = "Member";
    // set type
    item.syntax = {};
    if (doclet.type != undefined) {
      item.syntax.return = {
        type: [doclet.type.names[0]]
      };
    }
    // set syntax
    item.syntax.content = item.name;
  }

  function serialize() {
    var serializer = require("js-yaml");
    var fs = require("fs");
    var classes = {};
    var fileMap = {};
    if (!fs.existsSync(base)) {
      fs.mkdirSync(base);
    }
    items.forEach(function (i) {
      switch (i.type) {
        case "Class":
          classes[i.uid] = {
            items: [i],
            referenceMap: {}
          };
          fileMap[i.uid] = i.uid;
          break;
        case "Constructor":
        case "Function":
        case "Member":
          var parentId = i.parent || globalUid;
          var parent = classes[parentId];
          if (parent === undefined) {
            console.log(parentId + " is not a class, ignored.");
            break;
          }
          parent.items.push(i);
          if (parentId === globalUid) {
            (parent.items[0].children = parent.items[0].children || []).push(i.uid);
          }
          fileMap[i.uid] = parentId;
          (i.syntax.parameters || []).forEach(function (p) {
            (p.type || []).forEach(function (t) {
              classes[parentId].referenceMap[t] = true;
            });
          });
          if (i.syntax.return) {
            (i.syntax.return.type || []).forEach(function (t) {
              classes[parentId].referenceMap[t] = true;
            })
          }
          break;
      }
    });

    var toc = [];
    for (var id in classes) {
      var c = classes[id];
      // build references
      c.references = [];
      for (var r in c.referenceMap) {
        var f = fileMap[r];
        if (f !== undefined && f !== id) {
          c.references.push({
            uid: r,
            name: r.indexOf(".") == -1 ? r : r.substring(r.indexOf(".") + 1),
            fullName: r,
            isExternal: f === undefined
          });
        }
      }
      c.referenceMap = undefined;
      if (c.references.length == 0) {
        c.references = undefined;
      }

      // something wrong in js-yaml, workaround it by serialize and deserialize from JSON
      var c = JSON.parse(JSON.stringify(c));
      // replace \r, \n, space with dash
      var fileName = id.replace(/[ \n\r]/g, "-") + outputFileExt;
      if (fileName && fileName.split(".").length > 2) {
        fileName = fileName.split(".").splice(1).join(".");
      }
      fs.writeFileSync(base + '/' + fileName, yamlMime + '\n' + serializer.safeDump(c));
      console.log(fileName + " generated.");
      toc.push({
        uid: id,
        name: c.items[0].name
      });
    };
    toc.sort(function (a, b) {
      // sort classes alphabetically, but GLOBAL at last
      if (a.uid === globalUid) {
        return 1;
      }
      if (b.uid === globalUid) {
        return -1;
      }
      var nameA = a.name.toUpperCase();
      var nameB = b.name.toUpperCase();
      if (nameA < nameB) {
        return -1;
      }
      if (nameA > nameB) {
        return 1;
      }

      return 0;
    });

    fs.writeFileSync(base + "/toc.yml", serializer.safeDump(toc));
    console.log("toc.yml generated.");
  }

  var typeMap = {
    "member": handleMember,
    "function": handleFunction,
    "class": handleClass
  };

  exports.handlers = {
    newDoclet: function (e) {
      var doclet = e.doclet;
      // ignore anything whose parent is not a doclet
      // except it's a class made with help function
      if (doclet.memberof !== undefined && itemsMap[uidPrefix + doclet.memberof] === undefined && doclet.kind !== "class") {
        return;
      }
      // ignore unrecognized kind
      if (typeMap[doclet.kind] === undefined) {
        console.log("unrecognized kind: " + doclet.kind);
        return;
      }
      // ignore unexported global member
      if (doclet.memberof === undefined && doclet.kind != "class" && !(doclet.meta && doclet.meta.code && doclet.meta.code.name && doclet.meta.code.name.indexOf("exports") == 0)) {
        return;
      }
      // ignore inner function or member
      if (doclet.kind === "member" && doclet.scope === "inner") {
        return;
      }

      // ignore doclet without doucment
      if (doclet.undocumented === true) {
        return;
      }

      // ignore empty longname
      if (!doclet.longname) {
        return;
      }
      var parent = '';
      if (doclet.memberof === undefined && doclet.kind !== "class") {
        parent = "_global.";
      }
      // basic properties
      var item = {
        uid: uidPrefix + parent + doclet.longname,
        id: uidPrefix + parent + doclet.longname,
        parent: (doclet.memberof && doclet.kind !== "class") ? (uidPrefix + doclet.memberof) : undefined,
        name: doclet.name,
        summary: doclet.description ? dfm.convertLinkToGfm(doclet.description) : dfm.convertLinkToGfm(doclet.summary)
      };
      // set parent
      if (item.parent !== undefined) {
        var parent = itemsMap[item.parent];
        (parent.children = parent.children || []).push(item.uid);
      }
      // set full name
      item.fullName = (item.parent ? item.parent + "." : uidPrefix) + item.name;

      // set source info
      if (doclet.kind === "class") {
        setSourceInfo(item, doclet);
      }

      addItem(item);
      typeMap[doclet.kind](item, doclet);
    },
    parseBegin: function () {
      var fs = require('fs');
      var fse = require('fs-extra');
      var path = require('path');
      var config = fse.readJsonSync(jsdocConfigPath);

      // copy readme.md to index.md
      if (config.readme) {
        fse.copySync(config.readme, path.join(base, 'index.md'));
      }

      // parse package.json to use package name
      if (config.package) {
        var packageJson = fse.readJsonSync(config.package);
        if (packageJson && packageJson.name) {
          globalUid = packageJson.name + "." + globalUid;
          uidPrefix = packageJson.name + ".";
        }
      }
      items.push(
        {
          uid: globalUid,
          id: globalUid,
          name: "GLOBAL",
          fullName: "GLOBAL",
          type: "Class",
          summary: "global object",
          langs: ["js"]
        }
      )
    },
    parseComplete: function () {
      serialize();
      // no need to generate html, directly exit process
      process.exit(0);
    }
  };
})();
<|endoftext|>


<commit_before>define("PhenotypeSelectionUtils", [], function() {
  return {
    /*
      phenotype data structure:
      id <- an HPO id or arbitrary text
      isObserved <- boolean describing whether or not the phenotype was observed
      qualifiers: {
        spatial_pattern <- HPO ID
        severity <- HPO ID
      }
    */

    /**
     * Selects a phenotype. If the phenotype is already selected, do nothing.
     * @param  {object} phenotype         the phenotype. see object spec above.
     * @param  {string} autoSelectSrcDesc a string describing the reason for auto-selection of this phenotype, if applicable.
     */
    selectPhenotype: function(phenotype, autoSelectSrcDesc) {
      var _this = this;
      var addAutomaticSelectionIndicator = function(phenotypeEl) {
        var addedItem = $('current-phenotype-selection').down('label input[value="' + phenotypeEl.value + '"]');
        if (addedItem && autoSelectSrcDesc) {
          addedItem.up('label').insert({before : new Element('span', {
                                                               'class' : 'fa fa-bolt',
                                                               'title' : 'This phenotype was automatically added based on ' + autoSelectSrcDesc
          }).update(' ')});
        }
      };

      var existingEl = this._findFormElementForPhenotype(phenotype.id, !phenotype.isObserved);
      if (existingEl) {
        if (existingEl._ynpicker) {
          existingEl._ynpicker._select(phenotype.isObserved ? 'yes' : 'no');
        } else {
          existingEl.checked = true;
        }
        addAutomaticSelectionIndicator(existingEl);
      } else {
        var suggestWidget = $("quick-phenotype-search")._suggestWidget;
        if (!suggestWidget) {
           return null;
        }
        var id = phenotype.id;
        var searchUrl = new XWiki.Document('SolrService', 'PhenoTips').getURL("get", "q=" + id);
        new Ajax.Request(searchUrl, {
          method: 'get',
          onSuccess: function(transport) {
            var response = transport.responseJSON.rows[0];
            if (response) {
              var categories = "";
              if (!phenotype.isObserved) {
                categories += '<input type="hidden" name="fieldName" value="PhenoTips.PatientClass_0_negative_phenotype" class="no">';
              }
              categories += '';
              response.term_category.each(function(category){categories += '<input type="hidden" value="' + category + '">';});
              categories += "";
              var data = {
                id: id,
                value: response.name,
                category: categories,
                negative: !phenotype.isObserved
              };
              var title = response.name;
              suggestWidget.acceptEntry(data, title, title, true);

              existingEl = _this._findFormElementForPhenotype(phenotype.id, !phenotype.isObserved);
              addAutomaticSelectionIndicator(existingEl);
            }
          }
        });
      }
    },

    /**
     * Deselects a phenotype. If the phenotype is not selected, do nothing.
     * @param  {object} phenotype the phenotype. see object spec above.
     */
    deselectPhenotype: function(phenotype) {
      var phenotypeEl = this._findFormElementForPhenotype(phenotype.id, !phenotype.isObserved);
      if (phenotypeEl) {
        if (phenotypeEl) {
          phenotypeEl._ynpicker._onUnselect();
        } else {
          phenotypeEl.checked = false;
        }
      }
    },

    /**
     * Gets an array of phenotypes that are currently selected.
     * @return {array} phenotypes the selected phenotypes. see object spec above.
     */
    getSelectedPhenotypes: function() {
      return $$('div.phenotype .yes-no-picker').map(function(e) {
        var yes = e.down('.yes input');
        var no = e.down('.no input');
        /* Not a phenotype */
        if (yes.name === no.name) {
          return null;
        }
        var id = yes.value;
        var set = yes.checked || no.checked;
        if(set) {
          return {id: id, isObserved: yes.checked};
        } else {
          return null;
        }
      }).filter(function(e) { return e; });
    },

    /**
     * Updates a selected phenotype. If the phenotype is not selected, do nothing.
     */
    /*updateSelectedPhenotype: function(phenotype) {
    },*/

    _findFormElementForPhenotype: function(id, negative, subtype) {
      var result = null;
      if ($('prefix')) {
        result = $($('prefix').value + (negative ? 'negative_' : '') + (subtype ? subtype + '_' : '') + 'phenotype_' + id);
      }
      return result;
    },
  };
});
<commit_msg>[misc] remove some dead code<commit_after>define("PhenotypeSelectionUtils", [], function() {
  return {
    /*
      phenotype data structure:
      id <- an HPO id or arbitrary text
      isObserved <- boolean describing whether or not the phenotype was observed
      qualifiers: {
        spatial_pattern <- HPO ID
        severity <- HPO ID
      }
    */

    /**
     * Selects a phenotype. If the phenotype is already selected, do nothing.
     * @param  {object} phenotype         the phenotype. see object spec above.
     * @param  {string} autoSelectSrcDesc a string describing the reason for auto-selection of this phenotype, if applicable.
     */
    selectPhenotype: function(phenotype, autoSelectSrcDesc) {
      var _this = this;
      var addAutomaticSelectionIndicator = function(phenotypeEl) {
        var addedItem = $('current-phenotype-selection').down('label input[value="' + phenotypeEl.value + '"]');
        if (addedItem && autoSelectSrcDesc) {
          addedItem.up('label').insert({before : new Element('span', {
                                                               'class' : 'fa fa-bolt',
                                                               'title' : 'This phenotype was automatically added based on ' + autoSelectSrcDesc
          }).update(' ')});
        }
      };

      var existingEl = this._findFormElementForPhenotype(phenotype.id, !phenotype.isObserved);
      if (existingEl) {
        if (existingEl._ynpicker) {
          existingEl._ynpicker._select(phenotype.isObserved ? 'yes' : 'no');
        } else {
          existingEl.checked = true;
        }
        addAutomaticSelectionIndicator(existingEl);
      } else {
        var suggestWidget = $("quick-phenotype-search")._suggestWidget;
        if (!suggestWidget) {
           return null;
        }
        var id = phenotype.id;
        var searchUrl = new XWiki.Document('SolrService', 'PhenoTips').getURL("get", "q=" + id);
        new Ajax.Request(searchUrl, {
          method: 'get',
          onSuccess: function(transport) {
            var response = transport.responseJSON.rows[0];
            if (response) {
              var categories = "";
              if (!phenotype.isObserved) {
                categories += '<input type="hidden" name="fieldName" value="PhenoTips.PatientClass_0_negative_phenotype" class="no">';
              }
              categories += '';
              response.term_category.each(function(category){categories += '<input type="hidden" value="' + category + '">';});
              categories += "";
              var data = {
                id: id,
                value: response.name,
                category: categories,
                negative: !phenotype.isObserved
              };
              var title = response.name;
              suggestWidget.acceptEntry(data, title, title, true);

              existingEl = _this._findFormElementForPhenotype(phenotype.id, !phenotype.isObserved);
              addAutomaticSelectionIndicator(existingEl);
            }
          }
        });
      }
    },

    /**
     * Deselects a phenotype. If the phenotype is not selected, do nothing.
     * @param  {object} phenotype the phenotype. see object spec above.
     */
    deselectPhenotype: function(phenotype) {
      var phenotypeEl = this._findFormElementForPhenotype(phenotype.id, !phenotype.isObserved);
      if (phenotypeEl) {
        if (phenotypeEl) {
          phenotypeEl._ynpicker._onUnselect();
        } else {
          phenotypeEl.checked = false;
        }
      }
    },

    /**
     * Gets an array of phenotypes that are currently selected.
     * @return {array} phenotypes the selected phenotypes. see object spec above.
     */
    getSelectedPhenotypes: function() {
      return $$('div.phenotype .yes-no-picker').map(function(e) {
        var yes = e.down('.yes input');
        var no = e.down('.no input');
        /* Not a phenotype */
        if (yes.name === no.name) {
          return null;
        }
        var id = yes.value;
        var set = yes.checked || no.checked;
        if(set) {
          return {id: id, isObserved: yes.checked};
        } else {
          return null;
        }
      }).filter(function(e) { return e; });
    },

    _findFormElementForPhenotype: function(id, negative, subtype) {
      var result = null;
      if ($('prefix')) {
        result = $($('prefix').value + (negative ? 'negative_' : '') + (subtype ? subtype + '_' : '') + 'phenotype_' + id);
      }
      return result;
    },
  };
});
<|endoftext|>


<commit_before>const path = require('path')
const fs = require('fs')

const {
  sortDependencies,
  installDependencies,
  runLintFix,
  printMessage,
} = require('./utils')
const pkg = require('./package.json')

const templateVersion = pkg.version

const { addTestAnswers } = require('./scenarios')

module.exports = {
  metalsmith: {
    // When running tests for the template, this adds answers for the selected scenario
    before: addTestAnswers
  },
  helpers: {
    if_or(v1, v2, options) {

      if (v1 || v2) {
        return options.fn(this)
      }

      return options.inverse(this)
    },
    template_version() {
      return templateVersion
    },
  },

  prompts: {
    name: {
      when: 'isNotTest',
      type: 'string',
      required: true,
      message: 'Project name',
    },
    description: {
      when: 'isNotTest',
      type: 'string',
      required: false,
      message: 'Project description',
      default: 'A Vue.js project',
    },
    author: {
      when: 'isNotTest',
      type: 'string',
      message: 'Author',
    },
    build: {
      when: 'isNotTest',
      type: 'list',
      message: 'Vue build',
      choices: [
        {
          name: 'Runtime + Compiler: recommended for most users',
          value: 'standalone',
          short: 'standalone',
        },
        {
          name:
            'Runtime-only: about 6KB lighter min+gzip, but templates (or any Vue-specific HTML) are ONLY allowed in .vue files - render functions are required elsewhere',
          value: 'runtime',
          short: 'runtime',
        },
      ],
    },
    router: {
      when: 'isNotTest',
      type: 'confirm',
      message: 'Install vue-router?',
    },
    lint: {
      when: 'isNotTest',
      type: 'confirm',
      message: 'Use ESLint to lint your code?',
    },
    lintConfig: {
      when: 'isNotTest && lint',
      type: 'list',
      message: 'Pick an ESLint preset',
      choices: [
        {
          name: "Neonblack (https://www.npmjs.com/package/eslint-config-neonblack)",
          value: "neonblack",
          short: "Neonblack"
        },
        {
          name: 'Standard (https://github.com/standard/standard)',
          value: 'standard',
          short: 'Standard',
        },
        {
          name: 'Airbnb (https://github.com/airbnb/javascript)',
          value: 'airbnb',
          short: 'Airbnb',
        },
        {
          name: 'none (configure it yourself)',
          value: 'none',
          short: 'none',
        },
      ],
    },
    unit: {
      when: 'isNotTest',
      type: 'confirm',
      message: 'Set up unit tests',
    },
    runner: {
      when: 'isNotTest && unit',
      type: 'list',
      message: 'Pick a test runner',
      choices: [
        {
          name: 'Jest',
          value: 'jest',
          short: 'jest',
        },
        {
          name: 'Karma and Mocha',
          value: 'karma',
          short: 'karma',
        },
        {
          name: 'none (configure it yourself)',
          value: 'noTest',
          short: 'noTest',
        },
      ],
    },
    e2e: {
      when: 'isNotTest',
      type: 'confirm',
      message: 'Setup e2e tests with Nightwatch?',
    },
    autoInstall: {
      when: 'isNotTest',
      type: 'list',
      message:
        'Should we run `npm install` for you after the project has been created? (recommended)',
      choices: [
        {
          name: 'Yes, use NPM',
          value: 'npm',
          short: 'npm',
        },
        {
          name: 'Yes, use Yarn',
          value: 'yarn',
          short: 'yarn',
        },
        {
          name: 'No, I will handle that myself',
          value: false,
          short: 'no',
        },
      ],
    },
  },
  filters: {
    '.eslintrc.js': 'lint',
    '.eslintignore': 'lint',
    'config/test.env.js': 'unit || e2e',
    'build/webpack.test.conf.js': "unit && runner === 'karma'",
    'test/unit/**/*': 'unit',
    'test/unit/index.js': "unit && runner === 'karma'",
    'test/unit/jest.conf.js': "unit && runner === 'jest'",
    'test/unit/karma.conf.js': "unit && runner === 'karma'",
    'test/unit/specs/index.js': "unit && runner === 'karma'",
    'test/unit/setup.js': "unit && runner === 'jest'",
    'test/e2e/**/*': 'e2e',
    'src/router/**/*': 'router',
    "src/scss/bootstrap/**/*": "bootstrap"
  },
  complete: function(data, { chalk }) {
    const green = chalk.green

    sortDependencies(data, green)

    const cwd = path.join(process.cwd(), data.inPlace ? '' : data.destDirName)

    if (data.autoInstall) {
      installDependencies(cwd, data.autoInstall, green)
        .then(() => {
          return runLintFix(cwd, data, green)
        })
        .then(() => {
          printMessage(data, green)
        })
        .catch(e => {
          console.log(chalk.red('Error:'), e)
        })
    } else {
      printMessage(data, chalk)
    }
  },
}
<commit_msg>fix bootstrap<commit_after>const path = require('path')
const fs = require('fs')

const {
  sortDependencies,
  installDependencies,
  runLintFix,
  printMessage,
} = require('./utils')
const pkg = require('./package.json')

const templateVersion = pkg.version

const { addTestAnswers } = require('./scenarios')

module.exports = {
  metalsmith: {
    // When running tests for the template, this adds answers for the selected scenario
    before: addTestAnswers
  },
  helpers: {
    if_or(v1, v2, options) {

      if (v1 || v2) {
        return options.fn(this)
      }

      return options.inverse(this)
    },
    template_version() {
      return templateVersion
    },
  },

  prompts: {
    name: {
      when: 'isNotTest',
      type: 'string',
      required: true,
      message: 'Project name',
    },
    description: {
      when: 'isNotTest',
      type: 'string',
      required: false,
      message: 'Project description',
      default: 'A Vue.js project',
    },
    author: {
      when: 'isNotTest',
      type: 'string',
      message: 'Author',
    },
    build: {
      when: 'isNotTest',
      type: 'list',
      message: 'Vue build',
      choices: [
        {
          name: 'Runtime + Compiler: recommended for most users',
          value: 'standalone',
          short: 'standalone',
        },
        {
          name:
            'Runtime-only: about 6KB lighter min+gzip, but templates (or any Vue-specific HTML) are ONLY allowed in .vue files - render functions are required elsewhere',
          value: 'runtime',
          short: 'runtime',
        },
      ],
    },
    router: {
      when: 'isNotTest',
      type: 'confirm',
      message: 'Install vue-router?',
    },
    lint: {
      when: 'isNotTest',
      type: 'confirm',
      message: 'Use ESLint to lint your code?',
    },
    lintConfig: {
      when: 'isNotTest && lint',
      type: 'list',
      message: 'Pick an ESLint preset',
      choices: [
        {
          name: "Neonblack (https://www.npmjs.com/package/eslint-config-neonblack)",
          value: "neonblack",
          short: "Neonblack"
        },
        {
          name: 'Standard (https://github.com/standard/standard)',
          value: 'standard',
          short: 'Standard',
        },
        {
          name: 'Airbnb (https://github.com/airbnb/javascript)',
          value: 'airbnb',
          short: 'Airbnb',
        },
        {
          name: 'none (configure it yourself)',
          value: 'none',
          short: 'none',
        },
      ],
    },
    unit: {
      when: 'isNotTest',
      type: 'confirm',
      message: 'Set up unit tests',
    },
    runner: {
      when: 'isNotTest && unit',
      type: 'list',
      message: 'Pick a test runner',
      choices: [
        {
          name: 'Jest',
          value: 'jest',
          short: 'jest',
        },
        {
          name: 'Karma and Mocha',
          value: 'karma',
          short: 'karma',
        },
        {
          name: 'none (configure it yourself)',
          value: 'noTest',
          short: 'noTest',
        },
      ],
    },
    e2e: {
      when: 'isNotTest',
      type: 'confirm',
      message: 'Setup e2e tests with Nightwatch?',
    },
    bootstrap: {
      type: "confirm",
      message: "Do you want to use Bootstrap?"
    },
    autoInstall: {
      when: 'isNotTest',
      type: 'list',
      message:
        'Should we run `npm install` for you after the project has been created? (recommended)',
      choices: [
        {
          name: 'Yes, use NPM',
          value: 'npm',
          short: 'npm',
        },
        {
          name: 'Yes, use Yarn',
          value: 'yarn',
          short: 'yarn',
        },
        {
          name: 'No, I will handle that myself',
          value: false,
          short: 'no',
        },
      ],
    },
  },
  filters: {
    '.eslintrc.js': 'lint',
    '.eslintignore': 'lint',
    'config/test.env.js': 'unit || e2e',
    'build/webpack.test.conf.js': "unit && runner === 'karma'",
    'test/unit/**/*': 'unit',
    'test/unit/index.js': "unit && runner === 'karma'",
    'test/unit/jest.conf.js': "unit && runner === 'jest'",
    'test/unit/karma.conf.js': "unit && runner === 'karma'",
    'test/unit/specs/index.js': "unit && runner === 'karma'",
    'test/unit/setup.js': "unit && runner === 'jest'",
    'test/e2e/**/*': 'e2e',
    'src/router/**/*': 'router',
    "src/scss/bootstrap/**/*": "bootstrap"
  },
  complete: function(data, { chalk }) {
    const green = chalk.green

    sortDependencies(data, green)

    const cwd = path.join(process.cwd(), data.inPlace ? '' : data.destDirName)

    if (data.autoInstall) {
      installDependencies(cwd, data.autoInstall, green)
        .then(() => {
          return runLintFix(cwd, data, green)
        })
        .then(() => {
          printMessage(data, green)
        })
        .catch(e => {
          console.log(chalk.red('Error:'), e)
        })
    } else {
      printMessage(data, chalk)
    }
  },
}
<|endoftext|>


<commit_before>'use strict';

var default_env = {
  'result': [
    ['service', 'add',
     {'charm': 'cs:precise/wordpress-6',
       'id': 'blog', 'exposed': false}],
    ['service', 'add', {'charm': 'cs:precise/mysql-6',
       'id': 'my_db'}]],
  'op': 'delta'};

var default_endpoints = {
  'blog': {
    'requires': [
      {
        'interface': 'varnish',
        'optional': true,
        'limit': 2,
        'name': 'cache',
        'scope': 'global'
      },
      {
        'interface': 'mysql',
        'optional': false,
        'limit': 1,
        'name': 'db',
        'scope': 'global'
      }
    ],
    'provides': [
      {
        'interface': 'http',
        'optional': false,
        'limit': null,
        'name': 'url',
        'scope': 'global'
      }
    ]
  },
  'my_db': {
    'requires': [],
    'provides': [
      {
        'interface': 'mysql',
        'optional': false,
        'limit': null,
        'name': 'server',
        'scope': 'global'
      }
    ]
  }
};

// These are nominally based on improv sample.json delta stream with
// the addition of puppet subordinate relations.

var sample_endpoints = {"haproxy":{"requires":[{"interface":"http","limit":1,"optional":false,"name":"reverseproxy","scope":"global"}],"provides":[{"interface":"munin-node","limit":null,"optional":false,"name":"munin","scope":"global"},{"interface":"http","limit":null,"optional":false,"name":"website","scope":"global"}]},"mediawiki":{"requires":[{"interface":"mysql","limit":1,"optional":false,"name":"slave","scope":"global"},{"interface":"memcache","limit":1,"optional":false,"name":"cache","scope":"global"},{"interface":"mysql","limit":1,"optional":false,"name":"db","scope":"global"}],"provides":[{"interface":"http","limit":null,"optional":false,"name":"website","scope":"global"}]},"puppet":{"requires":[{"interface":"puppet","limit":1,"optional":false,"name":"puppetmaster","scope":"global"},{"interface":"juju-info","limit":1,"optional":false,"name":"juju-info","scope":"container"}],"provides":[]},"mysql":{"requires":[{"interface":"mysql-oneway-replication","limit":1,"optional":false,"name":"slave","scope":"global"}],"provides":[{"interface":"munin-node","limit":null,"optional":false,"name":"munin","scope":"global"},{"interface":"mysql","limit":null,"optional":false,"name":"db","scope":"global"},{"interface":"mysql-oneway-replication","limit":null,"optional":false,"name":"master","scope":"global"},{"interface":"mysql-shared","limit":null,"optional":false,"name":"shared-db","scope":"global"},{"interface":"local-monitors","limit":null,"optional":false,"name":"local-monitors","scope":"container"},{"interface":"mysql-root","limit":null,"optional":false,"name":"db-admin","scope":"global"},{"interface":"monitors","limit":null,"optional":false,"name":"monitors","scope":"global"}]},"wordpress":{"requires":[{"interface":"mount","limit":1,"optional":false,"name":"nfs","scope":"global"},{"interface":"memcache","limit":1,"optional":false,"name":"cache","scope":"global"},{"interface":"mysql","limit":1,"optional":false,"name":"db","scope":"global"}],"provides":[{"interface":"http","limit":null,"optional":false,"name":"website","scope":"global"}]},"memcached":{"requires":[],"provides":[{"interface":"munin-node","limit":null,"optional":false,"name":"munin","scope":"global"},{"interface":"memcache","limit":null,"optional":false,"name":"cache","scope":"global"}]}}

var sample_env = [
    ["service", "add", {"charm": "cs:precise/haproxy-7", "id": "haproxy"}], ["service", "add", {"charm": "cs:precise/mediawiki-3", "id": "mediawiki"}], ["service", "add", {"subordinate": true, "charm": "cs:precise/puppet-2", "id": "puppet"}], ["service", "add", {"charm": "cs:precise/mysql-6", "id": "mysql"}], ["service", "add", {"charm": "cs:precise/wordpress-7", "id": "wordpress"}], ["service", "add", {"charm": "cs:precise/memcached-1", "id": "memcached"}],
    ["relation", "add", {"interface": "mysql", "scope": "global", "endpoints": [["mysql", {"role": "server", "name": "db"}], ["mediawiki", {"role": "client", "name": "db"}]], "id": "relation-0000000002"}], ["relation", "add", {"interface": "memcache", "scope": "global", "endpoints": [["memcached", {"role": "server", "name": "cache"}], ["mediawiki", {"role": "client", "name": "cache"}]], "id": "relation-0000000003"}], ["relation", "add", {"interface": "mysql", "scope": "global", "endpoints": [["wordpress", {"role": "client", "name": "db"}], ["mysql", {"role": "server", "name": "db"}]], "id": "relation-0000000001"}], ["relation", "add", {"interface": "reversenginx", "scope": "global", "endpoints": [["wordpress", {"role": "peer", "name": "loadbalancer"}]], "id": "relation-0000000004"}], ["relation", "add", {"interface": "juju-info", "scope": "container", "endpoints": [["haproxy", {"role": "server", "name": "juju-info"}], ["puppet", {"role": "client", "name": "juju-info"}]], "id": "relation-0000000006"}]]

describe('Relation mapping logic', function() {
  var Y, juju, db, models;

  beforeEach(function(done) {
    Y = YUI(GlobalConfig).use(['juju-models',
                               'juju-tests-utils',
                               'juju-controllers'],
    function(Y) {
      juju = Y.namespace('juju');
      models = Y.namespace('juju.models');
      db = new (Y.namespace('juju.models')).Database();
      db.on_delta({data: default_env});
      done();
    });
  });

  afterEach(function(done) {
    db.destroy();
    done();
  });

  it('should be able find relatable services', function() {
    var service = db.services.getById('blog'),
        available = Y.Object.keys(models.getEndpoints(
            service, default_endpoints, db));

    available[0].should.equal('my_db');
    available.length.should.equal(1);

    service = db.services.getById('my_db');
    // Lookup by Value
    available = Y.Array.flatten(Y.Object.values(
        models.getEndpoints(service, default_endpoints, db)));
    available[0].service.should.equal('blog');
    available.length.should.equal(1);
  });

  it('should be able to find valid targets', function() {
    // populate with some sample relations
    db.reset();
    db.on_delta({data: {'op': 'delta', result: sample_env}});
    var service = db.services.getById('haproxy'),
      available = models.getEndpoints(service, sample_endpoints, db),
      available_svcs;
    available_svcs = Y.Object.keys(available);
    available_svcs.length.should.equal(2);
    available_svcs[0].should.equal('mediawiki');
    available_svcs[1].should.equal('wordpress');

    service = db.services.getById('puppet'),
    available = models.getEndpoints(service, sample_endpoints, db),
    available_svcs = Y.Object.keys(available);
    Y.Array.each(available, function(ep) {available_svcs.push(ep.service);});
    available_svcs.should.eql(
        ["mediawiki", "mysql", "wordpress", "memcached"]);
  });

  it('should be able find ignore existing relations services', function() {
    var blog = db.services.getById('blog'),
        endpoints = Y.Object.keys(
            models.getEndpoints(blog, default_endpoints, db));

    // Validate service level mappings
    endpoints[0].should.equal('my_db');

    // Force a relation delta
    db.on_delta({data: {
      result: [[
        'relation', 'add',
        {'interface': 'mysql',
          'scope': 'global', 'endpoints':
              [['my_db', {'role': 'server', 'name': 'db'}],
               ['blog', {'role': 'client', 'name': 'db'}]],
          'id': 'relation-0000000001'}]],
      op: 'delta'
    }});

    // Which means no valid endpoints.
    endpoints = Y.Object.keys(
        models.getEndpoints(blog, default_endpoints, db));
    endpoints.length.should.equal(0);
  });

});

<commit_msg>missing semis<commit_after>'use strict';

var default_env = {
  'result': [
    ['service', 'add',
     {'charm': 'cs:precise/wordpress-6',
       'id': 'blog', 'exposed': false}],
    ['service', 'add', {'charm': 'cs:precise/mysql-6',
       'id': 'my_db'}]],
  'op': 'delta'};

var default_endpoints = {
  'blog': {
    'requires': [
      {
        'interface': 'varnish',
        'optional': true,
        'limit': 2,
        'name': 'cache',
        'scope': 'global'
      },
      {
        'interface': 'mysql',
        'optional': false,
        'limit': 1,
        'name': 'db',
        'scope': 'global'
      }
    ],
    'provides': [
      {
        'interface': 'http',
        'optional': false,
        'limit': null,
        'name': 'url',
        'scope': 'global'
      }
    ]
  },
  'my_db': {
    'requires': [],
    'provides': [
      {
        'interface': 'mysql',
        'optional': false,
        'limit': null,
        'name': 'server',
        'scope': 'global'
      }
    ]
  }
};

// These are nominally based on improv sample.json delta stream with
// the addition of puppet subordinate relations.

var sample_endpoints = {"haproxy":{"requires":[{"interface":"http","limit":1,"optional":false,"name":"reverseproxy","scope":"global"}],"provides":[{"interface":"munin-node","limit":null,"optional":false,"name":"munin","scope":"global"},{"interface":"http","limit":null,"optional":false,"name":"website","scope":"global"}]},"mediawiki":{"requires":[{"interface":"mysql","limit":1,"optional":false,"name":"slave","scope":"global"},{"interface":"memcache","limit":1,"optional":false,"name":"cache","scope":"global"},{"interface":"mysql","limit":1,"optional":false,"name":"db","scope":"global"}],"provides":[{"interface":"http","limit":null,"optional":false,"name":"website","scope":"global"}]},"puppet":{"requires":[{"interface":"puppet","limit":1,"optional":false,"name":"puppetmaster","scope":"global"},{"interface":"juju-info","limit":1,"optional":false,"name":"juju-info","scope":"container"}],"provides":[]},"mysql":{"requires":[{"interface":"mysql-oneway-replication","limit":1,"optional":false,"name":"slave","scope":"global"}],"provides":[{"interface":"munin-node","limit":null,"optional":false,"name":"munin","scope":"global"},{"interface":"mysql","limit":null,"optional":false,"name":"db","scope":"global"},{"interface":"mysql-oneway-replication","limit":null,"optional":false,"name":"master","scope":"global"},{"interface":"mysql-shared","limit":null,"optional":false,"name":"shared-db","scope":"global"},{"interface":"local-monitors","limit":null,"optional":false,"name":"local-monitors","scope":"container"},{"interface":"mysql-root","limit":null,"optional":false,"name":"db-admin","scope":"global"},{"interface":"monitors","limit":null,"optional":false,"name":"monitors","scope":"global"}]},"wordpress":{"requires":[{"interface":"mount","limit":1,"optional":false,"name":"nfs","scope":"global"},{"interface":"memcache","limit":1,"optional":false,"name":"cache","scope":"global"},{"interface":"mysql","limit":1,"optional":false,"name":"db","scope":"global"}],"provides":[{"interface":"http","limit":null,"optional":false,"name":"website","scope":"global"}]},"memcached":{"requires":[],"provides":[{"interface":"munin-node","limit":null,"optional":false,"name":"munin","scope":"global"},{"interface":"memcache","limit":null,"optional":false,"name":"cache","scope":"global"}]}};

var sample_env = [
    ["service", "add", {"charm": "cs:precise/haproxy-7", "id": "haproxy"}], ["service", "add", {"charm": "cs:precise/mediawiki-3", "id": "mediawiki"}], ["service", "add", {"subordinate": true, "charm": "cs:precise/puppet-2", "id": "puppet"}], ["service", "add", {"charm": "cs:precise/mysql-6", "id": "mysql"}], ["service", "add", {"charm": "cs:precise/wordpress-7", "id": "wordpress"}], ["service", "add", {"charm": "cs:precise/memcached-1", "id": "memcached"}],
    ["relation", "add", {"interface": "mysql", "scope": "global", "endpoints": [["mysql", {"role": "server", "name": "db"}], ["mediawiki", {"role": "client", "name": "db"}]], "id": "relation-0000000002"}], ["relation", "add", {"interface": "memcache", "scope": "global", "endpoints": [["memcached", {"role": "server", "name": "cache"}], ["mediawiki", {"role": "client", "name": "cache"}]], "id": "relation-0000000003"}], ["relation", "add", {"interface": "mysql", "scope": "global", "endpoints": [["wordpress", {"role": "client", "name": "db"}], ["mysql", {"role": "server", "name": "db"}]], "id": "relation-0000000001"}], ["relation", "add", {"interface": "reversenginx", "scope": "global", "endpoints": [["wordpress", {"role": "peer", "name": "loadbalancer"}]], "id": "relation-0000000004"}], ["relation", "add", {"interface": "juju-info", "scope": "container", "endpoints": [["haproxy", {"role": "server", "name": "juju-info"}], ["puppet", {"role": "client", "name": "juju-info"}]], "id": "relation-0000000006"}]];

describe('Relation mapping logic', function() {
  var Y, juju, db, models;

  beforeEach(function(done) {
    Y = YUI(GlobalConfig).use(['juju-models',
                               'juju-tests-utils',
                               'juju-controllers'],
    function(Y) {
      juju = Y.namespace('juju');
      models = Y.namespace('juju.models');
      db = new (Y.namespace('juju.models')).Database();
      db.on_delta({data: default_env});
      done();
    });
  });

  afterEach(function(done) {
    db.destroy();
    done();
  });

  it('should be able find relatable services', function() {
    var service = db.services.getById('blog'),
        available = Y.Object.keys(models.getEndpoints(
            service, default_endpoints, db));

    available[0].should.equal('my_db');
    available.length.should.equal(1);

    service = db.services.getById('my_db');
    // Lookup by Value
    available = Y.Array.flatten(Y.Object.values(
        models.getEndpoints(service, default_endpoints, db)));
    available[0].service.should.equal('blog');
    available.length.should.equal(1);
  });

  it('should be able to find valid targets', function() {
    // populate with some sample relations
    db.reset();
    db.on_delta({data: {'op': 'delta', result: sample_env}});
    var service = db.services.getById('haproxy'),
      available = models.getEndpoints(service, sample_endpoints, db),
      available_svcs;
    available_svcs = Y.Object.keys(available);
    available_svcs.length.should.equal(2);
    available_svcs[0].should.equal('mediawiki');
    available_svcs[1].should.equal('wordpress');

    service = db.services.getById('puppet'),
    available = models.getEndpoints(service, sample_endpoints, db),
    available_svcs = Y.Object.keys(available);
    Y.Array.each(available, function(ep) {available_svcs.push(ep.service);});
    available_svcs.should.eql(
        ["mediawiki", "mysql", "wordpress", "memcached"]);
  });

  it('should be able find ignore existing relations services', function() {
    var blog = db.services.getById('blog'),
        endpoints = Y.Object.keys(
            models.getEndpoints(blog, default_endpoints, db));

    // Validate service level mappings
    endpoints[0].should.equal('my_db');

    // Force a relation delta
    db.on_delta({data: {
      result: [[
        'relation', 'add',
        {'interface': 'mysql',
          'scope': 'global', 'endpoints':
              [['my_db', {'role': 'server', 'name': 'db'}],
               ['blog', {'role': 'client', 'name': 'db'}]],
          'id': 'relation-0000000001'}]],
      op: 'delta'
    }});

    // Which means no valid endpoints.
    endpoints = Y.Object.keys(
        models.getEndpoints(blog, default_endpoints, db));
    endpoints.length.should.equal(0);
  });

});

<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import styled from '@emotion/styled';

import { Explorer, Router } from '@storybook/components';

const strip = (href, viewMode = 'components') => href.replace('#!', `/${viewMode}/`);

const StyledLink = React.memo(
  styled(Router.Link)({
    display: 'flex',
    alignItems: 'center',
    color: 'inherit',
    textDecoration: 'none',
  })
);
StyledLink.displayName = 'StyledLink';
const LeafLink = React.memo(({ href, children, ...rest }) => (
  <Router.Location>
    {({ viewMode }) => (
      <StyledLink to={strip(href, viewMode)} {...rest}>
        {children}
      </StyledLink>
    )}
  </Router.Location>
));

const StoriesPanel = React.memo(props => <Explorer allowClick {...props} Link={LeafLink} />);
StoriesPanel.propTypes = {
  stories: PropTypes.shape({}).isRequired,
  componentId: PropTypes.string.isRequired,
};

export { StoriesPanel as StoriesExplorer };
<commit_msg>Use correct prop in explorer.js<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import styled from '@emotion/styled';

import { Explorer, Router } from '@storybook/components';

const strip = (href, viewMode = 'components') => href.replace('#!', `/${viewMode}/`);

const StyledLink = React.memo(
  styled(Router.Link)({
    display: 'flex',
    alignItems: 'center',
    color: 'inherit',
    textDecoration: 'none',
  })
);
StyledLink.displayName = 'StyledLink';
const LeafLink = React.memo(({ href, children, ...rest }) => (
  <Router.Location>
    {({ viewMode }) => (
      <StyledLink to={strip(href, viewMode)} {...rest}>
        {children}
      </StyledLink>
    )}
  </Router.Location>
));

const StoriesPanel = React.memo(props => <Explorer allowClick {...props} LinkNode={LeafLink} />);
StoriesPanel.propTypes = {
  stories: PropTypes.shape({}).isRequired,
  componentId: PropTypes.string.isRequired,
};

export { StoriesPanel as StoriesExplorer };
<|endoftext|>


<commit_before>import React from 'react';
import { shallow } from 'enzyme';
import { render } from 'react-testing-library';

import { ThemeProvider, themes } from '@storybook/theming';
import ShortcutsScreen from './shortcuts';

// A limited set of keys we use in this test file
const shortcutKeys = {
  fullScreen: ['F'],
  togglePanel: ['S'],
  toggleNav: ['A'],
  toolbar: ['T'],
  search: ['/'],
  focusNav: ['1'],
  focusIframe: ['2'],
};

const makeActions = () => ({
  setShortcut: jest.fn(),
  restoreDefaultShortcut: jest.fn().mockImplementation(action => shortcutKeys[action]),
  restoreAllDefaultShortcuts: jest.fn().mockReturnValue(shortcutKeys),
});

describe('ShortcutsScreen', () => {
  it('renders correctly', () => {
    const comp = shallow(
      <ThemeProvider theme={themes.light}>
        <ShortcutsScreen shortcutKeys={shortcutKeys} {...makeActions()} />
      </ThemeProvider>
    );
    expect(comp).toExist();
  });

  it('handles a full mount', () => {
    const comp = render(
      <ThemeProvider theme={themes.light}>
        <ShortcutsScreen shortcutKeys={shortcutKeys} {...makeActions()} />
      </ThemeProvider>
    );
    expect(comp).toBeDefined();
    comp.unmount();
  });

  describe('onFocus', () => {
    it('calls setstate and clears the input on focus', () => {
      const comp = shallow(<ShortcutsScreen shortcutKeys={shortcutKeys} {...makeActions()} />);
      const instance = comp.instance();

      instance.onFocus('toolbar')();
      expect(comp.state('shortcutKeys').toolbar.shortcut).toBeNull();
      expect(comp.state('activeFeature')).toBe('toolbar');
    });
  });

  describe('onKeyDown', () => {
    it('does nothing if a modifier key is pressed', () => {
      const actions = makeActions();
      const comp = shallow(<ShortcutsScreen shortcutKeys={shortcutKeys} {...actions} />);
      const instance = comp.instance();
      instance.onFocus('focusIframe')();
      instance.onKeyDown({ isShift: true, key: 'Shift' });
      expect(actions.setShortcut).not.toHaveBeenCalled();
      expect(comp.state('shortcutKeys').focusIframe.shortcut).toBeNull();
    });

    it('changes the shortcut in state if a key is pressed', () => {
      const actions = makeActions();
      const comp = shallow(<ShortcutsScreen shortcutKeys={shortcutKeys} {...actions} />);
      const instance = comp.instance();
      instance.onFocus('focusIframe')();
      instance.onKeyDown({ key: 'P' });
      expect(actions.setShortcut).not.toHaveBeenCalled();
      expect(comp.state('shortcutKeys').focusIframe.shortcut).toEqual(['P']);
      expect(comp.state('shortcutKeys').focusIframe.error).toBe(false);
    });

    it('sets an error and the shortcut in state if a duplicate key is pressed', () => {
      const actions = makeActions();
      const comp = shallow(<ShortcutsScreen shortcutKeys={shortcutKeys} {...actions} />);
      const instance = comp.instance();
      instance.onFocus('focusIframe')();
      instance.onKeyDown({ key: 'F' });
      expect(actions.setShortcut).not.toHaveBeenCalled();
      expect(comp.state('shortcutKeys').focusIframe.shortcut).toEqual(['F']);
      expect(comp.state('shortcutKeys').focusIframe.error).toBe(true);
    });
  });

  describe('onBlur', () => {
    it('if the input is empty, restores the respective default', async () => {
      const actions = makeActions();
      const comp = shallow(<ShortcutsScreen shortcutKeys={shortcutKeys} {...actions} />);
      const instance = comp.instance();
      instance.onFocus('focusIframe')();
      await instance.onBlur();

      expect(actions.setShortcut).not.toHaveBeenCalled();
      expect(actions.restoreDefaultShortcut).toHaveBeenCalledWith('focusIframe');
      expect(comp.state('shortcutKeys').focusIframe.shortcut).toEqual(['2']);
      expect(comp.state('shortcutKeys').focusIframe.error).toBe(false);
    });

    it('if the shortcut is errored, restores the respective default', async () => {
      const actions = makeActions();
      const comp = shallow(<ShortcutsScreen shortcutKeys={shortcutKeys} {...actions} />);
      const instance = comp.instance();
      instance.onFocus('focusIframe')();
      instance.onKeyDown({ key: 'F' });
      await instance.onBlur();

      expect(actions.setShortcut).not.toHaveBeenCalled();
      expect(actions.restoreDefaultShortcut).toHaveBeenCalledWith('focusIframe');
      expect(comp.state('shortcutKeys').focusIframe.shortcut).toEqual(['2']);
      expect(comp.state('shortcutKeys').focusIframe.error).toBe(false);
    });

    it('it saves the shortcut if it is valid', () => {
      const actions = makeActions();
      const comp = shallow(<ShortcutsScreen shortcutKeys={shortcutKeys} {...actions} />);
      const instance = comp.instance();
      instance.onFocus('focusIframe')();
      instance.onKeyDown({ key: 'P' });
      instance.onBlur();

      expect(actions.setShortcut).toHaveBeenCalledWith('focusIframe', ['P']);
      expect(comp.state('shortcutKeys').focusIframe.shortcut).toEqual(['P']);
      expect(comp.state('shortcutKeys').focusIframe.error).toBe(false);
    });
  });

  describe('restoreDefaults', () => {
    it('if the input is empty, restores the respective default', async () => {
      const actions = makeActions();
      const comp = shallow(<ShortcutsScreen shortcutKeys={shortcutKeys} {...actions} />);
      const instance = comp.instance();
      instance.onFocus('focusIframe')();
      instance.onKeyDown({ key: 'P' });

      await comp.find('#restoreDefaultsHotkeys').simulate('click');
      expect(comp.state('shortcutKeys').focusIframe.shortcut).toEqual(['2']);
    });
  });
});
<commit_msg>FIX test<commit_after>import React from 'react';
import { shallow } from 'enzyme';
import { render } from 'react-testing-library';

import { ThemeProvider, themes } from '@storybook/theming';
import ShortcutsScreen from './shortcuts';

// A limited set of keys we use in this test file
const shortcutKeys = {
  fullScreen: ['F'],
  togglePanel: ['S'],
  toggleNav: ['A'],
  toolbar: ['T'],
  search: ['/'],
  focusNav: ['1'],
  focusIframe: ['2'],
};

const makeActions = () => ({
  setShortcut: jest.fn(),
  restoreDefaultShortcut: jest.fn().mockImplementation(action => shortcutKeys[action]),
  restoreAllDefaultShortcuts: jest.fn().mockReturnValue(shortcutKeys),
  onClose: jest.fn(),
});

describe('ShortcutsScreen', () => {
  it('renders correctly', () => {
    const comp = shallow(
      <ThemeProvider theme={themes.light}>
        <ShortcutsScreen shortcutKeys={shortcutKeys} {...makeActions()} />
      </ThemeProvider>
    );
    expect(comp).toExist();
  });

  it('handles a full mount', () => {
    const comp = render(
      <ThemeProvider theme={themes.light}>
        <ShortcutsScreen shortcutKeys={shortcutKeys} {...makeActions()} />
      </ThemeProvider>
    );
    expect(comp).toBeDefined();
    comp.unmount();
  });

  describe('onFocus', () => {
    it('calls setstate and clears the input on focus', () => {
      const comp = shallow(<ShortcutsScreen shortcutKeys={shortcutKeys} {...makeActions()} />);
      const instance = comp.instance();

      instance.onFocus('toolbar')();
      expect(comp.state('shortcutKeys').toolbar.shortcut).toBeNull();
      expect(comp.state('activeFeature')).toBe('toolbar');
    });
  });

  describe('onKeyDown', () => {
    it('does nothing if a modifier key is pressed', () => {
      const actions = makeActions();
      const comp = shallow(<ShortcutsScreen shortcutKeys={shortcutKeys} {...actions} />);
      const instance = comp.instance();
      instance.onFocus('focusIframe')();
      instance.onKeyDown({ isShift: true, key: 'Shift' });
      expect(actions.setShortcut).not.toHaveBeenCalled();
      expect(comp.state('shortcutKeys').focusIframe.shortcut).toBeNull();
    });

    it('changes the shortcut in state if a key is pressed', () => {
      const actions = makeActions();
      const comp = shallow(<ShortcutsScreen shortcutKeys={shortcutKeys} {...actions} />);
      const instance = comp.instance();
      instance.onFocus('focusIframe')();
      instance.onKeyDown({ key: 'P' });
      expect(actions.setShortcut).not.toHaveBeenCalled();
      expect(comp.state('shortcutKeys').focusIframe.shortcut).toEqual(['P']);
      expect(comp.state('shortcutKeys').focusIframe.error).toBe(false);
    });

    it('sets an error and the shortcut in state if a duplicate key is pressed', () => {
      const actions = makeActions();
      const comp = shallow(<ShortcutsScreen shortcutKeys={shortcutKeys} {...actions} />);
      const instance = comp.instance();
      instance.onFocus('focusIframe')();
      instance.onKeyDown({ key: 'F' });
      expect(actions.setShortcut).not.toHaveBeenCalled();
      expect(comp.state('shortcutKeys').focusIframe.shortcut).toEqual(['F']);
      expect(comp.state('shortcutKeys').focusIframe.error).toBe(true);
    });
  });

  describe('onBlur', () => {
    it('if the input is empty, restores the respective default', async () => {
      const actions = makeActions();
      const comp = shallow(<ShortcutsScreen shortcutKeys={shortcutKeys} {...actions} />);
      const instance = comp.instance();
      instance.onFocus('focusIframe')();
      await instance.onBlur();

      expect(actions.setShortcut).not.toHaveBeenCalled();
      expect(actions.restoreDefaultShortcut).toHaveBeenCalledWith('focusIframe');
      expect(comp.state('shortcutKeys').focusIframe.shortcut).toEqual(['2']);
      expect(comp.state('shortcutKeys').focusIframe.error).toBe(false);
    });

    it('if the shortcut is errored, restores the respective default', async () => {
      const actions = makeActions();
      const comp = shallow(<ShortcutsScreen shortcutKeys={shortcutKeys} {...actions} />);
      const instance = comp.instance();
      instance.onFocus('focusIframe')();
      instance.onKeyDown({ key: 'F' });
      await instance.onBlur();

      expect(actions.setShortcut).not.toHaveBeenCalled();
      expect(actions.restoreDefaultShortcut).toHaveBeenCalledWith('focusIframe');
      expect(comp.state('shortcutKeys').focusIframe.shortcut).toEqual(['2']);
      expect(comp.state('shortcutKeys').focusIframe.error).toBe(false);
    });

    it('it saves the shortcut if it is valid', () => {
      const actions = makeActions();
      const comp = shallow(<ShortcutsScreen shortcutKeys={shortcutKeys} {...actions} />);
      const instance = comp.instance();
      instance.onFocus('focusIframe')();
      instance.onKeyDown({ key: 'P' });
      instance.onBlur();

      expect(actions.setShortcut).toHaveBeenCalledWith('focusIframe', ['P']);
      expect(comp.state('shortcutKeys').focusIframe.shortcut).toEqual(['P']);
      expect(comp.state('shortcutKeys').focusIframe.error).toBe(false);
    });
  });

  describe('restoreDefaults', () => {
    it('if the input is empty, restores the respective default', async () => {
      const actions = makeActions();
      const comp = shallow(<ShortcutsScreen shortcutKeys={shortcutKeys} {...actions} />);
      const instance = comp.instance();
      instance.onFocus('focusIframe')();
      instance.onKeyDown({ key: 'P' });

      await comp.find('#restoreDefaultsHotkeys').simulate('click');
      expect(comp.state('shortcutKeys').focusIframe.shortcut).toEqual(['2']);
    });
  });
});
<|endoftext|>


<commit_before>module('lively.store.tests.Interface').requires('lively.TestFramework', 'lively.store.Interface').toRun(function() {

AsyncTestCase.subclass('lively.store.tests.Interface.TestCase',
'running', {
    tearDown: function($super) {
        $super();
        lively.store.flushCache();
    }
},
'helper', {
    createWebSpy: function() {
        var spy  = this.webSpy = {
            putUrl: null, putContent: null, putCount: 0,
            getCount: 0, getUrl: null,
            deleteCount: 0, deleteUrl: null,
            status: null, lastWebResource: null
        }
        this.webSpy.statusAndContentOnGet = function(status, content, delay) {
            function update(webR) { webR.status = status; webR.content = content; }
            lively.bindings.connect(this, 'lastWebResource', update, 'call', {
                updater: function($upd, webR) {
                    if (!webR) return;
                    if (delay === undefined) $upd(null, webR)
                    else $upd.bind(null,null. webR).delay(delay);
                }, varMapping: {delay: delay}, removeAfterUpdate: true
            });
        }
        this.spyInClass(WebResource, 'put', function(source, mimeType, options) {
            spy.lastWebResource = this;
            spy.putContent = source;
            spy.putUrl = this.getURL();
            spy.putCount++;
            return this;
        });
        this.spyInClass(WebResource, 'get', function() {
            spy.lastWebResource = this;
            spy.getUrl = this.getURL();
            spy.getCount++;
            return this;
        });
        this.spyInClass(WebResource, 'del', function() {
            spy.lastWebResource = this;
            spy.deleteUrl = this.getURL();
            spy.deleteCount++;
            return this;
        });
    }
});

lively.store.tests.Interface.TestCase.subclass('lively.store.tests.Interface.ObjectStorage',
'tests', {
    test01SimpleGetAndSet: function() {
        var testObject = {storeTestObj: true},
            db = lively.store.get({id: this.currentSelector, type: 'ObjectStorage'});
        db.set("foo", testObject);
        var retrieved = db.get("foo", testObject);
        this.assertIdentity(testObject, retrieved, 'retrieved not identical to stored');
        this.done();
    },

    test02NamedDBs: function() {
        var testObject = {storeTestObj: true},
            db1 = lively.store.get({id: this.currentSelector, type: 'ObjectStorage'});
        db1.set("foo", testObject);
        var db2 = lively.store.get({id: this.currentSelector}),
            retrieved = db2.get("foo", testObject)
        this.assertIdentity(testObject, retrieved, 'retrieved not identical to stored');
        this.done();
    }
});

lively.store.tests.Interface.TestCase.subclass('lively.store.tests.Interface.FileStorage',
'running', {
    setUp: function($super) {
        $super();
        this.createWebSpy();
    }
},
'tests', {
    test01SaveAndLoadFromFile: function() {
        var url = URL.source.withFilename("foo.db"),
            db = lively.store.get({
                id: this.currentSelector, type: "FileStorage",
                url: url
            });
        db.set('xyz');
        this.assertEquals('xyz', this.webSpy.putContent);
        this.assertEquals(url, this.webSpy.putUrl);
        this.assertEquals(1, this.webSpy.putCount, "put count");
        // sync get
        this.webSpy.statusAndContentOnGet({}, 'xyz');
        var retrieved1 = db.get();
        this.assertEquals(1, this.webSpy.getCount, "get count 1");
        this.assertEquals(url, this.webSpy.getUrl);
        this.assertEquals('xyz', retrieved1, "retrieved1");
        // get via callback
        var retrieved2;
        this.webSpy.statusAndContentOnGet({}, 'xyz');
        db.get(function(err, data) { retrieved2 = data; });
        this.assertEquals(2, this.webSpy.getCount, "get count 2");
        this.assertEquals('xyz', retrieved2, 'retrieved2');
        this.done();
    }
});

lively.store.tests.Interface.TestCase.subclass('lively.store.tests.Interface.CouchDBStorage',
'running', {
    shouldRun: false,
    setUp: function($super) {
        $super();
        this.createWebSpy();
    }
},
'tests', {
    xtest01SimpleGetAndSet: function() {
        var testObject = {val: 12345},
            dbName = this.currentSelector.toLowerCase(),
            db = lively.store.get({id: dbName, type: 'CouchDBStorage'});
        db.set("foo", testObject);
        var url = URL.nodejsBase.withFilename("couchdb/" + dbName + '/foo');
        this.assertEquals(1, this.webSpy.putCount);
        this.assertEquals(url, this.webSpy.putUrl);
        this.assertEquals(JSON.stringify(testObject), this.webSpy.putContent);
        var retrieved = db.get("foo", testObject);
        this.assertEquals(testObject.val, retrieved.val,
                          'retrieved not identical to stored ' + retrieved);
        this.assertEquals(1, this.webSpy.getCount);
        this.assertEquals(url, this.webSpy.getUrl);
        this.done();
    },

    test02CreateAndRemoveStore: function() {
        var dbName = this.currentSelector.toLowerCase(),
            dbURL = URL.nodejsBase.withFilename('couchdb/' + dbName + '/'),
            db = lively.store.get({id: dbName, type: 'CouchDBStorage'});
        db.ensureExistance();
        this.assertEquals(1, this.webSpy.putCount);
        this.assertEquals(dbURL, this.webSpy.putUrl);
        db.remove();
        this.assertEquals(1, this.webSpy.deleteCount);
        this.assertEquals(dbURL, this.webSpy.deleteUrl);
        this.done();
    }

});

lively.store.tests.Interface.TestCase.subclass('lively.store.tests.Interface.ObjectRepository',
'running', {

    setUp: function($super) {
        $super();
        this.createWebSpy();
    }

},
'tests', {

    test01QueryObjectRecords: function() {
        var repo = new lively.store.ObjectRepository(URL.root),
            d = new Date(),
            querySpec = {paths: ['foo.js'], date: d, attributes: ['path', 'date']},
            recordsFromRepo = [{path: 'foo.js', date: d.toISOString()}],
            receivedRecords;
        this.webSpy.statusAndContentOnGet({isDone: Functions.True, isSuccess: Functions.True}, JSON.stringify(recordsFromRepo));
        repo.getRecords(querySpec, function(err, result) { receivedRecords = result; });
        this.waitFor(function() { return !!receivedRecords; }, 10, function() {
            var expectedURL = URL.nodejsBase.withFilename('ObjectRepositoryServer/').withQuery({
                getRecords: encodeURIComponent(JSON.stringify(querySpec))
            });
            this.assertEquals(1, this.webSpy.getCount, "get count 1");
            this.assertEquals(expectedURL, this.webSpy.getUrl);
            // this.assertEqualState(recordsFromRepo, receivedRecords, 'records');
            this.done()
        });
    },

    test02QueryObjectRecordsSync: function() {
        var repo = new lively.store.ObjectRepository(URL.root),
            d = new Date(),
            querySpec = {paths: ['foo.js'], date: d, attributes: ['path', 'date']},
            recordsFromRepo = [{path: 'foo.js', date: d.toISOString()}],
            receivedRecords;
        this.webSpy.statusAndContentOnGet({isDone: Functions.True, isSuccess: Functions.True}, JSON.stringify(recordsFromRepo));
        var receivedRecords = repo.getRecords(querySpec);
        var expectedURL = URL.nodejsBase.withFilename('ObjectRepositoryServer/').withQuery({
            getRecords: encodeURIComponent(JSON.stringify(querySpec))
        });
        this.assertEquals(1, this.webSpy.getCount, "get count 1");
        this.assertEquals(expectedURL, this.webSpy.getUrl);
    }

});

}); // end of module
<commit_msg>Making non-async test in async test cases pass<commit_after>module('lively.store.tests.Interface').requires('lively.TestFramework', 'lively.store.Interface').toRun(function() {

AsyncTestCase.subclass('lively.store.tests.Interface.TestCase',
'running', {
    tearDown: function($super) {
        $super();
        lively.store.flushCache();
    }
},
'helper', {
    createWebSpy: function() {
        var spy  = this.webSpy = {
            putUrl: null, putContent: null, putCount: 0,
            getCount: 0, getUrl: null,
            deleteCount: 0, deleteUrl: null,
            status: null, lastWebResource: null
        }
        this.webSpy.statusAndContentOnGet = function(status, content, delay) {
            function update(webR) { webR.status = status; webR.content = content; }
            lively.bindings.connect(this, 'lastWebResource', update, 'call', {
                updater: function($upd, webR) {
                    if (!webR) return;
                    if (delay === undefined) $upd(null, webR)
                    else $upd.bind(null,null. webR).delay(delay);
                }, varMapping: {delay: delay}, removeAfterUpdate: true
            });
        }
        this.spyInClass(WebResource, 'put', function(source, mimeType, options) {
            spy.lastWebResource = this;
            spy.putContent = source;
            spy.putUrl = this.getURL();
            spy.putCount++;
            return this;
        });
        this.spyInClass(WebResource, 'get', function() {
            spy.lastWebResource = this;
            spy.getUrl = this.getURL();
            spy.getCount++;
            return this;
        });
        this.spyInClass(WebResource, 'del', function() {
            spy.lastWebResource = this;
            spy.deleteUrl = this.getURL();
            spy.deleteCount++;
            return this;
        });
    }
});

lively.store.tests.Interface.TestCase.subclass('lively.store.tests.Interface.ObjectStorage',
'tests', {
    test01SimpleGetAndSet: function() {
        var testObject = {storeTestObj: true},
            db = lively.store.get({id: this.currentSelector, type: 'ObjectStorage'});
        db.set("foo", testObject);
        var retrieved = db.get("foo", testObject);
        this.assertIdentity(testObject, retrieved, 'retrieved not identical to stored');
        this.done();
    },

    test02NamedDBs: function() {
        var testObject = {storeTestObj: true},
            db1 = lively.store.get({id: this.currentSelector, type: 'ObjectStorage'});
        db1.set("foo", testObject);
        var db2 = lively.store.get({id: this.currentSelector}),
            retrieved = db2.get("foo", testObject)
        this.assertIdentity(testObject, retrieved, 'retrieved not identical to stored');
        this.done();
    }
});

lively.store.tests.Interface.TestCase.subclass('lively.store.tests.Interface.FileStorage',
'running', {
    setUp: function($super) {
        $super();
        this.createWebSpy();
    }
},
'tests', {
    test01SaveAndLoadFromFile: function() {
        var url = URL.source.withFilename("foo.db"),
            db = lively.store.get({
                id: this.currentSelector, type: "FileStorage",
                url: url
            });
        db.set('xyz');
        this.assertEquals('xyz', this.webSpy.putContent);
        this.assertEquals(url, this.webSpy.putUrl);
        this.assertEquals(1, this.webSpy.putCount, "put count");
        // sync get
        this.webSpy.statusAndContentOnGet({}, 'xyz');
        var retrieved1 = db.get();
        this.assertEquals(1, this.webSpy.getCount, "get count 1");
        this.assertEquals(url, this.webSpy.getUrl);
        this.assertEquals('xyz', retrieved1, "retrieved1");
        // get via callback
        var retrieved2;
        this.webSpy.statusAndContentOnGet({}, 'xyz');
        db.get(function(err, data) { retrieved2 = data; });
        this.assertEquals(2, this.webSpy.getCount, "get count 2");
        this.assertEquals('xyz', retrieved2, 'retrieved2');
        this.done();
    }
});

lively.store.tests.Interface.TestCase.subclass('lively.store.tests.Interface.CouchDBStorage',
'running', {
    shouldRun: false,
    setUp: function($super) {
        $super();
        this.createWebSpy();
    }
},
'tests', {
    xtest01SimpleGetAndSet: function() {
        var testObject = {val: 12345},
            dbName = this.currentSelector.toLowerCase(),
            db = lively.store.get({id: dbName, type: 'CouchDBStorage'});
        db.set("foo", testObject);
        var url = URL.nodejsBase.withFilename("couchdb/" + dbName + '/foo');
        this.assertEquals(1, this.webSpy.putCount);
        this.assertEquals(url, this.webSpy.putUrl);
        this.assertEquals(JSON.stringify(testObject), this.webSpy.putContent);
        var retrieved = db.get("foo", testObject);
        this.assertEquals(testObject.val, retrieved.val,
                          'retrieved not identical to stored ' + retrieved);
        this.assertEquals(1, this.webSpy.getCount);
        this.assertEquals(url, this.webSpy.getUrl);
        this.done();
    },

    test02CreateAndRemoveStore: function() {
        var dbName = this.currentSelector.toLowerCase(),
            dbURL = URL.nodejsBase.withFilename('couchdb/' + dbName + '/'),
            db = lively.store.get({id: dbName, type: 'CouchDBStorage'});
        db.ensureExistance();
        this.assertEquals(1, this.webSpy.putCount);
        this.assertEquals(dbURL, this.webSpy.putUrl);
        db.remove();
        this.assertEquals(1, this.webSpy.deleteCount);
        this.assertEquals(dbURL, this.webSpy.deleteUrl);
        this.done();
    }

});

lively.store.tests.Interface.TestCase.subclass('lively.store.tests.Interface.ObjectRepository',
'running', {

    setUp: function($super) {
        $super();
        this.createWebSpy();
    }

},
'tests', {

    test01QueryObjectRecords: function() {
        var repo = new lively.store.ObjectRepository(URL.root),
            d = new Date(),
            querySpec = {paths: ['foo.js'], date: d, attributes: ['path', 'date']},
            recordsFromRepo = [{path: 'foo.js', date: d.toISOString()}],
            receivedRecords;
        this.webSpy.statusAndContentOnGet({isDone: Functions.True, isSuccess: Functions.True}, JSON.stringify(recordsFromRepo));
        repo.getRecords(querySpec, function(err, result) { receivedRecords = result; });
        this.waitFor(function() { return !!receivedRecords; }, 10, function() {
            var expectedURL = URL.nodejsBase.withFilename('ObjectRepositoryServer/').withQuery({
                getRecords: encodeURIComponent(JSON.stringify(querySpec))
            });
            this.assertEquals(1, this.webSpy.getCount, "get count 1");
            this.assertEquals(expectedURL, this.webSpy.getUrl);
            // this.assertEqualState(recordsFromRepo, receivedRecords, 'records');
            this.done()
        });
    },

    test02QueryObjectRecordsSync: function() {
        var repo = new lively.store.ObjectRepository(URL.root),
            d = new Date(),
            querySpec = {paths: ['foo.js'], date: d, attributes: ['path', 'date']},
            recordsFromRepo = [{path: 'foo.js', date: d.toISOString()}],
            receivedRecords;
        this.webSpy.statusAndContentOnGet({isDone: Functions.True, isSuccess: Functions.True}, JSON.stringify(recordsFromRepo));
        var receivedRecords = repo.getRecords(querySpec);
        var expectedURL = URL.nodejsBase.withFilename('ObjectRepositoryServer/').withQuery({
            getRecords: encodeURIComponent(JSON.stringify(querySpec))
        });
        this.assertEquals(1, this.webSpy.getCount, "get count 1");
        this.assertEquals(expectedURL, this.webSpy.getUrl);
        this.done(); // FIXME: this test is not async!
    }

});

}); // end of module
<|endoftext|>