Best JavaScript code snippet using mountebank
medidasCrecimientoController.js
Source:medidasCrecimientoController.js  
1import medidasCrecimiento from "../models/medidasCrecimientoModel.js";2import asyncHandler from "express-async-handler";3// * ENDPOINTS GROWTH STAGE4// handleResponse: Manejador para los datos recibidos por consulta a la base de datos5function handleResponse(data, res) {6  if (data) {7    res.status(200).json(data);8  } else {9    res.status(404).json({ message: "Error fetching data." });10    res.status(404);11    throw new Error("Error fetching the years.");12  }13}14function manageFilters(query, variables) {15  if (variables && variables.length > 0) {16    for (let i = 0; i < variables.length; i++) {17      if (18        variables[i].value == "toxemia" ||19        variables[i].value == "Embarazomultiple" ||20        variables[i].value == "primipara" ||21        variables[i].value == "cesarea"22      ) {23        query[variables[i].value] = 1;24      }25      if (variables[i].value == "adolescentes") {26        query.edadmama = {27          $lte: 19,28        };29      }30      if (variables[i].value == "mayores") {31        query.edadmama = {32          $gte: 35,33        };34      }35      if (variables[i].value == "nivelmama") {36        query.nivelmama = variables[i].filter.includes("primaria")37          ? 138          : variables[i].filter.includes("secundaria")39          ? 240          : 3;41      }42      if (variables[i].value == "pesomama") {43        query.pesomama = {44          $gte: parseInt(variables[i].desde),45          $lte: parseInt(variables[i].hasta),46        };47      }48      if (variables[i].value == "tallamama") {49        query.tallamama = {50          $gte: parseInt(variables[i].desde),51          $lte: parseInt(variables[i].hasta),52        };53      }54      if (variables[i].value == "pesopapa") {55        query.pesopapa = {56          $gte: parseInt(variables[i].desde),57          $lte: parseInt(variables[i].hasta),58        };59      }60      if (variables[i].value == "tallapapa") {61        query.tallapapa = {62          $gte: parseInt(variables[i].desde),63          $lte: parseInt(variables[i].hasta),64        };65      }66      if (variables[i].value == "percapitasalariominimo") {67        query.percapitasalariominimo = {68          $gte: parseInt(variables[i].desde),69          $lte: parseInt(variables[i].hasta),70        };71      }72      if (variables[i].value == "pesoalnacer") {73        query.pesoalnacer = {74          $gte: parseInt(variables[i].desde),75          $lte: parseInt(variables[i].hasta),76        };77      }78      if (variables[i].value == "tallamama") {79        query.tallaalnacer = {80          $gte: parseInt(variables[i].desde),81          $lte: parseInt(variables[i].hasta),82        };83      }84      if (variables[i].value == "pcalnacer") {85        query.pcalnacer = {86          $gte: parseInt(variables[i].desde),87          $lte: parseInt(variables[i].hasta),88        };89      }90      if (variables[i].value == "tallapapa") {91        query.tallapapa = {92          $gte: parseInt(variables[i].desde),93          $lte: parseInt(variables[i].hasta),94        };95      }96      if (variables[i].value == "sexo") {97        query.nivelmama = variables[i].filter.includes("niño") ? 1 : 2;98      }99    }100  }101  return query;102}103// RCIUFreqDiasH104export const RCIUFreqDiasH = asyncHandler(async (req, res) => {105  const initialYear = req.body.inicio;106  const finalYear = req.body.fin;107  const variables = req.body.vars;108  var data = [];109  const queryInitial = {110    ANOCAT: { $gte: initialYear, $lte: finalYear },111    edadgestacional: { $lt: 37 },112  };113  const query = manageFilters(queryInitial, variables);114  data = await medidasCrecimiento115    .find(query)116    .select([117      "ANOCAT",118      "RCIUpesoFenton",119      "edadgestacional",120      "TotalDiasHospitalizacion",121    ])122    .lean();123  const dataVis = {};124  const dataWith = [];125  const dataWithout = [];126  const datasets = [];127  dataWith.push(128    Math.round(129      (data130        .filter(131          (obj) =>132            obj.ANOCAT >= initialYear &&133            obj.ANOCAT <= finalYear &&134            obj.RCIUpesoFenton == 1 &&135            obj.edadgestacional <= 32136        )137        .reduce((a, b) => a + (b["TotalDiasHospitalizacion"] || 0), 0) /138        data.filter(139          (obj) =>140            obj.ANOCAT >= initialYear &&141            obj.ANOCAT <= finalYear &&142            obj.RCIUpesoFenton == 1 &&143            obj.edadgestacional <= 32144        ).length) *145        100146    ) / 100147  );148  dataWith.push(149    Math.round(150      (data151        .filter(152          (obj) =>153            obj.ANOCAT >= initialYear &&154            obj.ANOCAT <= finalYear &&155            obj.RCIUpesoFenton == 1 &&156            obj.edadgestacional >= 33 &&157            obj.edadgestacional <= 34158        )159        .reduce((a, b) => a + (b["TotalDiasHospitalizacion"] || 0), 0) /160        data.filter(161          (obj) =>162            obj.ANOCAT >= initialYear &&163            obj.ANOCAT <= finalYear &&164            obj.RCIUpesoFenton == 1 &&165            obj.edadgestacional >= 33 &&166            obj.edadgestacional <= 34167        ).length) *168        100169    ) / 100170  );171  dataWith.push(172    Math.round(173      (data174        .filter(175          (obj) =>176            obj.ANOCAT >= initialYear &&177            obj.ANOCAT <= finalYear &&178            obj.RCIUpesoFenton == 1 &&179            obj.edadgestacional >= 34 &&180            obj.edadgestacional < 37181        )182        .reduce((a, b) => a + (b["TotalDiasHospitalizacion"] || 0), 0) /183        data.filter(184          (obj) =>185            obj.ANOCAT >= initialYear &&186            obj.ANOCAT <= finalYear &&187            obj.RCIUpesoFenton == 1 &&188            obj.edadgestacional >= 34 &&189            obj.edadgestacional < 37190        ).length) *191        100192    ) / 100193  );194  dataWith.push(195    Math.round(196      (data197        .filter(198          (obj) =>199            obj.ANOCAT >= initialYear &&200            obj.ANOCAT <= finalYear &&201            obj.RCIUpesoFenton == 1 &&202            obj.edadgestacional >= 37203        )204        .reduce((a, b) => a + (b["TotalDiasHospitalizacion"] || 0), 0) /205        data.filter(206          (obj) =>207            obj.ANOCAT >= initialYear &&208            obj.ANOCAT <= finalYear &&209            obj.RCIUpesoFenton == 1 &&210            obj.edadgestacional >= 37211        ).length) *212        100213    ) / 100214  );215  dataWithout.push(216    Math.round(217      (data218        .filter(219          (obj) =>220            obj.ANOCAT >= initialYear &&221            obj.ANOCAT <= finalYear &&222            obj.RCIUpesoFenton == 0 &&223            obj.edadgestacional <= 32224        )225        .reduce((a, b) => a + (b["TotalDiasHospitalizacion"] || 0), 0) /226        data.filter(227          (obj) =>228            obj.ANOCAT >= initialYear &&229            obj.ANOCAT <= finalYear &&230            obj.RCIUpesoFenton == 0 &&231            obj.edadgestacional <= 32232        ).length) *233        100234    ) / 100235  );236  dataWithout.push(237    Math.round(238      (data239        .filter(240          (obj) =>241            obj.ANOCAT >= initialYear &&242            obj.ANOCAT <= finalYear &&243            obj.RCIUpesoFenton == 0 &&244            obj.edadgestacional >= 33 &&245            obj.edadgestacional <= 34246        )247        .reduce((a, b) => a + (b["TotalDiasHospitalizacion"] || 0), 0) /248        data.filter(249          (obj) =>250            obj.ANOCAT >= initialYear &&251            obj.ANOCAT <= finalYear &&252            obj.RCIUpesoFenton == 0 &&253            obj.edadgestacional >= 33 &&254            obj.edadgestacional <= 34255        ).length) *256        100257    ) / 100258  );259  dataWithout.push(260    Math.round(261      (data262        .filter(263          (obj) =>264            obj.ANOCAT >= initialYear &&265            obj.ANOCAT <= finalYear &&266            obj.RCIUpesoFenton == 0 &&267            obj.edadgestacional >= 34 &&268            obj.edadgestacional < 37269        )270        .reduce((a, b) => a + (b["TotalDiasHospitalizacion"] || 0), 0) /271        data.filter(272          (obj) =>273            obj.ANOCAT >= initialYear &&274            obj.ANOCAT <= finalYear &&275            obj.RCIUpesoFenton == 0 &&276            obj.edadgestacional >= 34 &&277            obj.edadgestacional < 37278        ).length) *279        100280    ) / 100281  );282  dataWithout.push(283    Math.round(284      (data285        .filter(286          (obj) =>287            obj.ANOCAT >= initialYear &&288            obj.ANOCAT <= finalYear &&289            obj.RCIUpesoFenton == 0 &&290            obj.edadgestacional >= 37291        )292        .reduce((a, b) => a + (b["TotalDiasHospitalizacion"] || 0), 0) /293        data.filter(294          (obj) =>295            obj.ANOCAT >= initialYear &&296            obj.ANOCAT <= finalYear &&297            obj.RCIUpesoFenton == 0 &&298            obj.edadgestacional >= 37299        ).length) *300        100301    ) / 100302  );303  datasets.push({304    label: "con RCIU",305    data: dataWith,306    backgroundColor: "#0E7FA6",307  });308  datasets.push({309    label: "sin RCIU",310    data: dataWithout,311    backgroundColor: "#70D6BC",312  });313  dataVis.labels = [314    "< 32 semanas",315    "33-34 semanas",316    "34-37 semanas",317    "> 37 semanas",318  ];319  dataVis.datasets = datasets;320  handleResponse(dataVis, res);321});322// RCIUFreqUCI323export const RCIUFreqUCI = asyncHandler(async (req, res) => {324  const initialYear = req.body.inicio;325  const finalYear = req.body.fin;326  const isPremature = req.body.prem;327  const variables = req.body.vars;328  const yearsInterval = [];329  const queryInitial = {330    ANOCAT: { $gte: initialYear, $lte: finalYear },331    edadgestacional: isPremature == "true" ? { $lt: 37 } : { $gt: 37 },332  };333  const query = manageFilters(queryInitial, variables);334  const data = await medidasCrecimiento335    .find(query)336    .select(["ANOCAT", "RCIUpesoFenton", "UCI"])337    .lean();338  for (let index = initialYear; index < parseInt(finalYear) + 1; index++) {339    yearsInterval.push(index.toString());340  }341  const size = data.length;342  const dataPoints1 = [];343  const dataPoints2 = [];344  const dataVis = {};345  dataVis.colorSet =346    isPremature == "true" ? "customColorSetPrem" : "customColorSetTerm";347  dataVis.axisX = {348    labelFontFamily: "arial",349    interval: 5,350    valueFormatString: "####",351  };352  dataVis.axisY = {353    labelFontFamily: "arial",354    titleFontFamily: "arial",355    title: "Cantidad",356  };357  dataVis.toolTip = {358    fontFamily: "arial",359    shared: true,360  };361  dataVis.zoomEnabled = true;362  dataVis.zoomType = "xy";363  for (let i = 0; i < yearsInterval.length; i++) {364    dataPoints1.push({365      x: parseInt(yearsInterval[i]),366      y: data.filter(367        (obj) =>368          obj.ANOCAT == yearsInterval[i] &&369          obj.UCI == 1 &&370          obj.RCIUpesoFenton == 1371      ).length,372      relative:373        data.filter(374          (obj) =>375            obj.ANOCAT == yearsInterval[i] &&376            obj.UCI == 1 &&377            obj.RCIUpesoFenton == 1378        ).length / size,379    });380    dataPoints2.push({381      x: parseInt(yearsInterval[i]),382      y: data.filter(383        (obj) =>384          obj.ANOCAT == yearsInterval[i] &&385          obj.UCI == 1 &&386          obj.RCIUpesoFenton == 0387      ).length,388      relative:389        data.filter(390          (obj) =>391            obj.ANOCAT == yearsInterval[i] &&392            obj.UCI == 1 &&393            obj.RCIUpesoFenton == 0394        ).length / size,395    });396  }397  dataVis.data = [];398  // dataVis.height = 140;399  dataVis.legend = {400    horizontalAlign: "top",401    verticalAlign: "top",402    fontFamily: "arial",403  };404  dataVis.data.push({405    type: "stackedBar",406    name: isPremature == "true" ? "con RCIU prematuros" : "con RCIU a término",407    showInLegend: true,408    dataPoints: dataPoints1,409  });410  dataVis.data.push({411    type: "stackedBar",412    name: isPremature == "true" ? "sin RCIU prematuros" : "sin RCIU a término",413    showInLegend: true,414    dataPoints: dataPoints2,415  });416  handleResponse(dataVis, res);417});418// RCIUFreqEGEntrada419export const RCIUFreqEGEntrada = asyncHandler(async (req, res) => {420  const initialYear = req.body.inicio;421  const finalYear = req.body.fin;422  const isEntrada = req.body.entrada;423  const variables = req.body.vars;424  const yearsInterval = [];425  const queryInitial = {426    ANOCAT: { $gte: initialYear, $lte: finalYear },427    edadgestacional: { $lt: 37 },428  };429  const query = manageFilters(queryInitial, variables);430  const data = await medidasCrecimiento431    .find(query)432    .select([433      "ANOCAT",434      "RCIUpesoFenton",435      "edadgestacionalalaentrada",436      "edadsalidaPC",437    ])438    .lean();439  for (let index = initialYear; index < parseInt(finalYear) + 1; index++) {440    yearsInterval.push(index.toString());441  }442  const dataPoints1 = [];443  const dataPoints2 = [];444  const dataVis = {};445  dataVis.colorSet =446    isEntrada == "true" ? "customColorSetPrem" : "customColorSetTerm";447  dataVis.axisX = {448    title: "Años",449    titleFontFamily: "arial",450    labelFontFamily: "arial",451    titleFontStyle: "bold",452  };453  dataVis.axisY = {454    title:455      isEntrada == "true"456        ? "Promedio edad gestacional entrada"457        : "Promedio edad gestacional salida",458    titleFontFamily: "arial",459    labelFontFamily: "arial",460    titleFontStyle: "bold",461  };462  dataVis.toolTip = {463    fontFamily: "arial",464  };465  dataVis.zoomEnabled = true;466  dataVis.zoomType = "xy";467  for (let i = 0; i < yearsInterval.length; i++) {468    dataPoints1.push({469      x: i,470      y:471        data472          .filter(473            (obj) => obj.ANOCAT == yearsInterval[i] && obj.RCIUpesoFenton == 1474          )475          .reduce(476            (a, b) =>477              a +478              (b[479                isEntrada == "true"480                  ? "edadgestacionalalaentrada"481                  : "edadsalidaPC"482              ] || 0),483            0484          ) /485        data.filter(486          (obj) => obj.ANOCAT == yearsInterval[i] && obj.RCIUpesoFenton == 1487        ).length,488    });489    dataPoints2.push({490      x: i,491      y:492        data493          .filter(494            (obj) => obj.ANOCAT == yearsInterval[i] && obj.RCIUpesoFenton == 0495          )496          .reduce(497            (a, b) =>498              a +499              (b[500                isEntrada == "true"501                  ? "edadgestacionalalaentrada"502                  : "edadsalidaPC"503              ] || 0),504            0505          ) /506        data.filter(507          (obj) => obj.ANOCAT == yearsInterval[i] && obj.RCIUpesoFenton == 0508        ).length,509    });510  }511  dataVis.data = [];512  dataVis.height = 300;513  dataVis.legend = {514    horizontalAlign: "top",515    verticalAlign: "top",516    fontFamily: "arial",517  };518  dataVis.data.push({519    type: "spline",520    markerSize: 5,521    connectNullData: true,522    name: "con RCIU",523    showInLegend: true,524    dataPoints: dataPoints1,525  });526  dataVis.data.push({527    type: "spline",528    markerSize: 5,529    connectNullData: true,530    name: "sin RCIU",531    showInLegend: true,532    dataPoints: dataPoints2,533  });534  handleResponse(dataVis, res);535});536// RCIUPromPesoPMC537export const RCIUPromPesoPMC = asyncHandler(async (req, res) => {538  const initialYear = req.body.inicio;539  const finalYear = req.body.fin;540  const graph = req.body.graph;541  const yearsInterval = [];542  const variables = req.body.vars;543  const queryInitial = {544    ANOCAT: { $gte: initialYear, $lte: finalYear },545    edadgestacional: { $lt: 37 },546  };547  const query = manageFilters(queryInitial, variables);548  const data = await medidasCrecimiento549    .find(query)550    .select([551      "ANOCAT",552      "RCIUpesoFenton",553      "RCIUpesoFentonentrada",554      "edadgestacional",555      "pesoalaentrada",556      "PesosalidaPC",557    ])558    .lean();559  for (let index = initialYear; index < parseInt(finalYear) + 1; index++) {560    yearsInterval.push(index.toString());561  }562  const dataVis = {};563  const dataEntrada = [];564  const dataSalida = [];565  const datasets = [];566  for (let i = 0; i < yearsInterval.length; i++) {567    dataEntrada.push(568      Math.round(569        (data570          .filter(571            (obj) =>572              obj.ANOCAT == yearsInterval[i] &&573              (graph == "1"574                ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 1575                : graph == "2"576                ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 0577                : obj.RCIUpesoFenton == 1)578          )579          .reduce((a, b) => a + (b["pesoalaentrada"] || 0), 0) /580          data.filter(581            (obj) =>582              obj.ANOCAT == yearsInterval[i] &&583              (graph == "1"584                ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 1585                : graph == "2"586                ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 0587                : obj.RCIUpesoFenton == 1)588          ).length) *589          100590      ) / 100591    );592    dataSalida.push(593      Math.round(594        (data595          .filter(596            (obj) =>597              obj.ANOCAT == yearsInterval[i] &&598              (graph == "1"599                ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 1600                : graph == "2"601                ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 0602                : obj.RCIUpesoFenton == 1)603          )604          .reduce((a, b) => a + (b["PesosalidaPC"] || 0), 0) /605          data.filter(606            (obj) =>607              obj.ANOCAT == yearsInterval[i] &&608              (graph == "1"609                ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 1610                : graph == "2"611                ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 0612                : obj.RCIUpesoFenton == 1)613          ).length) *614          100615      ) / 100616    );617  }618  datasets.push({619    label: "Peso entrada programa canguro",620    data: dataEntrada,621    backgroundColor:622      graph == 1 ? "#0E7FA6" : graph == 2 ? "#FF955B" : "#e7e72d",623  });624  datasets.push({625    label: "Peso salida programa canguro",626    data: dataSalida,627    backgroundColor:628      graph == 1 ? "#70D6BC" : graph == 2 ? "#A6330A" : "#1fd567",629  });630  dataVis.labels = yearsInterval;631  dataVis.datasets = datasets;632  handleResponse(dataVis, res);633});634// RCIUOxiEntrada635export const RCIUOxiEntrada = asyncHandler(async (req, res) => {636  const initialYear = req.body.inicio;637  const finalYear = req.body.fin;638  const variables = req.body.vars;639  const yearsInterval = [];640  const queryInitial = {641    ANOCAT: { $gte: initialYear, $lte: finalYear },642    edadgestacional: { $lt: 37 },643    oxigenoentrada: 1,644  };645  const query = manageFilters(queryInitial, variables);646  const data = await medidasCrecimiento647    .find(query)648    .select(["ANOCAT", "RCIUpesoFenton", "oxigenoentrada"])649    .lean();650  for (let index = initialYear; index < parseInt(finalYear) + 1; index++) {651    yearsInterval.push(index.toString());652  }653  const dataPoints = [];654  const dataVis = {};655  dataVis.colorSet = "customColorSetPrem";656  dataVis.axisX = {657    title: "Presencia de RCIU",658    titleFontFamily: "arial",659    labelFontFamily: "arial",660    titleFontStyle: "bold",661  };662  dataVis.axisY = {663    title: "Número de bebés",664    titleFontFamily: "arial",665    labelFontFamily: "arial",666    titleFontStyle: "bold",667  };668  dataVis.toolTip = {669    content: "{label}: {y} neonatos ({relative}%)",670    fontFamily: "arial",671  };672  const size = data.length;673  dataVis.zoomEnabled = true;674  dataVis.zoomType = "xy";675  dataPoints.push({676    label: "con RCIU",677    y: data.filter(678      (obj) =>679        obj.ANOCAT >= initialYear &&680        obj.ANOCAT <= finalYear &&681        obj.RCIUpesoFenton == 1682    ).length,683    relative:684      Math.round(685        (data.filter(686          (obj) =>687            obj.ANOCAT >= initialYear &&688            obj.ANOCAT <= finalYear &&689            obj.RCIUpesoFenton == 1690        ).length /691          size) *692          100 *693          100694      ) / 100,695  });696  dataPoints.push({697    label: "sin RCIU",698    y: data.filter(699      (obj) =>700        obj.ANOCAT >= initialYear &&701        obj.ANOCAT <= finalYear &&702        obj.RCIUpesoFenton == 0703    ).length,704    relative:705      Math.round(706        (data.filter(707          (obj) =>708            obj.ANOCAT >= initialYear &&709            obj.ANOCAT <= finalYear &&710            obj.RCIUpesoFenton == 0711        ).length /712          size) *713          100 *714          100715      ) / 100,716  });717  dataVis.data = [];718  dataVis.height = 260;719  dataVis.data.push({720    type: "column",721    dataPoints: dataPoints,722  });723  handleResponse(dataVis, res);724});725// RCIULecheMaterna726export const RCIULecheMaterna = asyncHandler(async (req, res) => {727  const initialYear = req.body.inicio;728  const finalYear = req.body.fin;729  const variables = req.body.vars;730  const yearsInterval = [];731  const queryInitial = {732    ANOCAT: { $gte: initialYear, $lte: finalYear },733    edadgestacional: { $lt: 37 },734  };735  const query = manageFilters(queryInitial, variables);736  const data = await medidasCrecimiento737    .find(query)738    .select([739      "ANOCAT",740      "RCIUpesoFenton",741      "alimentacion.sem40",742      "alimentacion.mes3",743      "alimentacion.mes6",744      "alimentacion.mes9",745      "alimentacion.mes12",746    ])747    .lean();748  for (let index = initialYear; index < parseInt(finalYear) + 1; index++) {749    yearsInterval.push(index.toString());750  }751  const dataVis = {};752  const dataWith = [];753  const dataWithout = [];754  const datasets = [];755  dataWith.push(756    data.filter(757      (obj) =>758        obj.ANOCAT >= initialYear &&759        obj.ANOCAT <= finalYear &&760        obj.RCIUpesoFenton == 1 &&761        obj["alimentacion"] &&762        obj["alimentacion"]["sem40"] != 3763    ).length764  );765  dataWith.push(766    data.filter(767      (obj) =>768        obj.ANOCAT >= initialYear &&769        obj.ANOCAT <= finalYear &&770        obj.RCIUpesoFenton == 1 &&771        obj["alimentacion"] &&772        obj["alimentacion"]["mes3"] != 3773    ).length774  );775  dataWith.push(776    data.filter(777      (obj) =>778        obj.ANOCAT >= initialYear &&779        obj.ANOCAT <= finalYear &&780        obj.RCIUpesoFenton == 1 &&781        obj["alimentacion"] &&782        obj["alimentacion"]["mes6"] != 3783    ).length784  );785  dataWith.push(786    data.filter(787      (obj) =>788        obj.ANOCAT >= initialYear &&789        obj.ANOCAT <= finalYear &&790        obj.RCIUpesoFenton == 1 &&791        obj["alimentacion"] &&792        obj["alimentacion"]["mes9"] != 3793    ).length794  );795  dataWith.push(796    data.filter(797      (obj) =>798        obj.ANOCAT >= initialYear &&799        obj.ANOCAT <= finalYear &&800        obj.RCIUpesoFenton == 1 &&801        obj["alimentacion"] &&802        obj["alimentacion"]["mes12"] != 3803    ).length804  );805  dataWithout.push(806    data.filter(807      (obj) =>808        obj.ANOCAT >= initialYear &&809        obj.ANOCAT <= finalYear &&810        obj.RCIUpesoFenton == 0 &&811        obj["alimentacion"] &&812        obj["alimentacion"]["sem40"] != 3813    ).length814  );815  dataWithout.push(816    data.filter(817      (obj) =>818        obj.ANOCAT >= initialYear &&819        obj.ANOCAT <= finalYear &&820        obj.RCIUpesoFenton == 0 &&821        obj["alimentacion"] &&822        obj["alimentacion"]["mes3"] != 3823    ).length824  );825  dataWithout.push(826    data.filter(827      (obj) =>828        obj.ANOCAT >= initialYear &&829        obj.ANOCAT <= finalYear &&830        obj.RCIUpesoFenton == 0 &&831        obj["alimentacion"] &&832        obj["alimentacion"]["mes6"] != 3833    ).length834  );835  dataWithout.push(836    data.filter(837      (obj) =>838        obj.ANOCAT >= initialYear &&839        obj.ANOCAT <= finalYear &&840        obj.RCIUpesoFenton == 0 &&841        obj["alimentacion"] &&842        obj["alimentacion"]["mes9"] != 3843    ).length844  );845  dataWithout.push(846    data.filter(847      (obj) =>848        obj.ANOCAT >= initialYear &&849        obj.ANOCAT <= finalYear &&850        obj.RCIUpesoFenton == 0 &&851        obj["alimentacion"] &&852        obj["alimentacion"]["mes12"] != 3853    ).length854  );855  datasets.push({856    label: "con RCIU",857    data: dataWith,858    backgroundColor: "#0E7FA6",859  });860  datasets.push({861    label: "sin RCIU",862    data: dataWithout,863    backgroundColor: "#FF955B",864  });865  dataVis.labels = ["semana 40", "mes 3", "mes 6", "mes 9", "mes 12"];866  dataVis.datasets = datasets;867  handleResponse(dataVis, res);868});869// RCIULecheMaternaTime870export const RCIULecheMaternaTime = asyncHandler(async (req, res) => {871  const initialYear = req.body.inicio;872  const finalYear = req.body.fin;873  const tiempo = req.body.tiempo;874  const variables = req.body.vars;875  const yearsInterval = [];876  const queryInitial = {877    ANOCAT: { $gte: initialYear, $lte: finalYear },878    edadgestacional: { $lt: 37 },879  };880  const query = manageFilters(queryInitial, variables);881  const data = await medidasCrecimiento882    .find(query)883    .select([884      "ANOCAT",885      "RCIUpesoFenton",886      tiempo == "40"887        ? "alimentacion.sem40"888        : tiempo == "3"889        ? "alimentacion.mes3"890        : tiempo == "6"891        ? "alimentacion.mes6"892        : tiempo == "9"893        ? "alimentacion.mes9"894        : "alimentacion.mes12",895    ])896    .lean();897  for (let index = initialYear; index < parseInt(finalYear) + 1; index++) {898    yearsInterval.push(index.toString());899  }900  const dataPoints1 = [];901  const dataPoints2 = [];902  const dataVis = {};903  dataVis.colorSet = "customColorSetPrem";904  dataVis.axisX = {905    title: "Años",906    titleFontFamily: "arial",907    labelFontFamily: "arial",908    titleFontStyle: "bold",909  };910  dataVis.axisY = {911    title: "Frecuencia relativa",912    titleFontFamily: "arial",913    labelFontFamily: "arial",914    titleFontStyle: "bold",915  };916  dataVis.toolTip = {917    fontFamily: "arial",918  };919  dataVis.zoomEnabled = true;920  dataVis.zoomType = "xy";921  for (let i = 0; i < yearsInterval.length; i++) {922    dataPoints1.push({923      x: i,924      y:925        Math.round(926          (data.filter(927            (obj) =>928              obj.ANOCAT == yearsInterval[i] &&929              obj.RCIUpesoFenton == 1 &&930              obj.alimentacion &&931              (tiempo == "40"932                ? obj.alimentacion.sem40 != 3933                : tiempo == "3"934                ? obj.alimentacion.mes3 != 3935                : tiempo == "6"936                ? obj.alimentacion.mes6 != 3937                : tiempo == "9"938                ? obj.alimentacion.mes9 != 3939                : obj.alimentacion.mes12 != 3)940          ).length /941            data.filter(942              (obj) => obj.ANOCAT == yearsInterval[i] && obj.RCIUpesoFenton == 1943            ).length) *944            100 *945            100946        ) / 100,947    });948    dataPoints2.push({949      x: i,950      y:951        Math.round(952          (data.filter(953            (obj) =>954              obj.ANOCAT == yearsInterval[i] &&955              obj.RCIUpesoFenton == 0 &&956              obj.alimentacion &&957              (tiempo == "40"958                ? obj.alimentacion.sem40 != 3959                : tiempo == "3"960                ? obj.alimentacion.mes3 != 3961                : tiempo == "6"962                ? obj.alimentacion.mes6 != 3963                : tiempo == "9"964                ? obj.alimentacion.mes9 != 3965                : obj.alimentacion.mes12 != 3)966          ).length /967            data.filter(968              (obj) => obj.ANOCAT == yearsInterval[i] && obj.RCIUpesoFenton == 0969            ).length) *970            100 *971            100972        ) / 100,973    });974  }975  dataVis.data = [];976  dataVis.height = 300;977  dataVis.legend = {978    horizontalAlign: "top",979    verticalAlign: "top",980    fontFamily: "arial",981  };982  dataVis.data.push({983    type: "spline",984    markerSize: 5,985    connectNullData: true,986    name: "con RCIU",987    showInLegend: true,988    dataPoints: dataPoints1,989  });990  dataVis.data.push({991    type: "spline",992    markerSize: 5,993    connectNullData: true,994    name: "sin RCIU",995    showInLegend: true,996    dataPoints: dataPoints2,997  });998  handleResponse(dataVis, res);999});1000// RCIUAbsLecheMaternaTime1001export const RCIUAbsLecheMaternaTime = asyncHandler(async (req, res) => {1002  const initialYear = req.body.inicio;1003  const finalYear = req.body.fin;1004  const tiempo = req.body.tiempo;1005  const rciu = req.body.rciu;1006  const variables = req.body.vars;1007  const yearsInterval = [];1008  const queryInitial = {1009    ANOCAT: { $gte: initialYear, $lte: finalYear },1010    edadgestacional: { $lt: 37 },1011  };1012  const query = manageFilters(queryInitial, variables);1013  const data = await medidasCrecimiento1014    .find(query)1015    .select([1016      "ANOCAT",1017      "RCIUpesoFenton",1018      tiempo == "40"1019        ? "alimentacion.sem40"1020        : tiempo == "3"1021        ? "alimentacion.mes3"1022        : tiempo == "6"1023        ? "alimentacion.mes6"1024        : tiempo == "9"1025        ? "alimentacion.mes9"1026        : "alimentacion.mes12",1027    ])1028    .lean();1029  for (let index = initialYear; index < parseInt(finalYear) + 1; index++) {1030    yearsInterval.push(index.toString());1031  }1032  const dataPoints = [];1033  const dataVis = {};1034  dataVis.colorSet =1035    rciu == "1" ? "customColorSetWith" : "customColorSetWithout";1036  dataVis.axisX = {1037    title: "Años",1038    titleFontFamily: "arial",1039    labelFontFamily: "arial",1040    titleFontStyle: "bold",1041  };1042  dataVis.axisY = {1043    title: "Frecuencia Absoluta",1044    titleFontFamily: "arial",1045    labelFontFamily: "arial",1046    titleFontStyle: "bold",1047  };1048  dataVis.toolTip = {1049    content: "{label}: {y} neonatos",1050    fontFamily: "arial",1051  };1052  dataVis.zoomEnabled = true;1053  dataVis.zoomType = "xy";1054  for (let i = 0; i < yearsInterval.length; i++) {1055    dataPoints.push({1056      label: yearsInterval[i],1057      y: data.filter(1058        (obj) =>1059          obj.ANOCAT == yearsInterval[i] &&1060          (rciu == "1" ? obj.RCIUpesoFenton == 1 : obj.RCIUpesoFenton == 0) &&1061          obj.alimentacion &&1062          (tiempo == "40"1063            ? obj.alimentacion.sem40 != 31064            : tiempo == "3"1065            ? obj.alimentacion.mes3 != 31066            : tiempo == "6"1067            ? obj.alimentacion.mes6 != 31068            : tiempo == "9"1069            ? obj.alimentacion.mes9 != 31070            : obj.alimentacion.mes12 != 3)1071      ).length,1072    });1073  }1074  dataVis.data = [];1075  dataVis.height = 150;1076  dataVis.data.push({1077    type: "column",1078    dataPoints: dataPoints,1079  });1080  handleResponse(dataVis, res);1081});1082// parallelCoordsPMC1083export const parallelCoordsPMC = asyncHandler(async (req, res) => {1084  const initialYear = req.body.inicio;1085  const finalYear = req.body.fin;1086  const graph = req.body.graph;1087  const variables = req.body.vars;1088  const yearsInterval = [];1089  const queryInitial = {1090    ANOCAT: { $gte: initialYear, $lte: finalYear },1091    edadgestacional: { $lt: 37 },1092  };1093  const query = manageFilters(queryInitial, variables);1094  const data = await medidasCrecimiento1095    .find(query)1096    .select([1097      "ANOCAT",1098      "RCIUpesoFenton",1099      "RCIUpesoFentonentrada",1100      "pesoalaentrada",1101      "tallaalaentrada",1102      "PCalaentrada",1103      "edadgestacionalalaentrada",1104    ])1105    .lean();1106  for (let index = initialYear; index < parseInt(finalYear) + 1; index++) {1107    yearsInterval.push(index.toString());1108  }1109  const dataParallel = [];1110  for (let i = 0; i < yearsInterval.length; i++) {1111    dataParallel.push({1112      año: yearsInterval[i],1113      EG:1114        Math.round(1115          (data1116            .filter(1117              (obj) =>1118                obj.ANOCAT == yearsInterval[i] &&1119                (graph == "1"1120                  ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 11121                  : graph == "2"1122                  ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 01123                  : obj.RCIUpesoFenton == 1)1124            )1125            .reduce((a, b) => a + (b["edadgestacionalalaentrada"] || 0), 0) /1126            data.filter(1127              (obj) =>1128                obj.ANOCAT == yearsInterval[i] &&1129                (graph == "1"1130                  ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 11131                  : graph == "2"1132                  ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 01133                  : obj.RCIUpesoFenton == 1)1134            ).length) *1135            1001136        ) / 100,1137      "peso (gr)":1138        Math.round(1139          (data1140            .filter(1141              (obj) =>1142                obj.ANOCAT == yearsInterval[i] &&1143                (graph == "1"1144                  ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 11145                  : graph == "2"1146                  ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 01147                  : obj.RCIUpesoFenton == 1)1148            )1149            .reduce((a, b) => a + (b["pesoalaentrada"] || 0), 0) /1150            data.filter(1151              (obj) =>1152                obj.ANOCAT == yearsInterval[i] &&1153                (graph == "1"1154                  ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 11155                  : graph == "2"1156                  ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 01157                  : obj.RCIUpesoFenton == 1)1158            ).length) *1159            1001160        ) / 100,1161      "talla (cm)":1162        Math.round(1163          (data1164            .filter(1165              (obj) =>1166                obj.ANOCAT == yearsInterval[i] &&1167                (graph == "1"1168                  ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 11169                  : graph == "2"1170                  ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 01171                  : obj.RCIUpesoFenton == 1)1172            )1173            .reduce((a, b) => a + (b["tallaalaentrada"] || 0), 0) /1174            data.filter(1175              (obj) =>1176                obj.ANOCAT == yearsInterval[i] &&1177                (graph == "1"1178                  ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 11179                  : graph == "2"1180                  ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 01181                  : obj.RCIUpesoFenton == 1)1182            ).length) *1183            1001184        ) / 100,1185      "pc (cm)":1186        Math.round(1187          (data1188            .filter(1189              (obj) =>1190                obj.ANOCAT == yearsInterval[i] &&1191                (graph == "1"1192                  ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 11193                  : graph == "2"1194                  ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 01195                  : obj.RCIUpesoFenton == 1)1196            )1197            .reduce((a, b) => a + (b["PCalaentrada"] || 0), 0) /1198            data.filter(1199              (obj) =>1200                obj.ANOCAT == yearsInterval[i] &&1201                (graph == "1"1202                  ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 11203                  : graph == "2"1204                  ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 01205                  : obj.RCIUpesoFenton == 1)1206            ).length) *1207            1001208        ) / 100,1209      // color: Math.floor(Math.random() * (10 - 1 + 1) + 1),1210    });1211  }1212  handleResponse(dataParallel, res);1213});1214// parallelCoordsLecheMaterna1215export const parallelCoordsLecheMaterna = asyncHandler(async (req, res) => {1216  const initialYear = req.body.inicio;1217  const finalYear = req.body.fin;1218  const time = req.body.time;1219  const rciu = req.body.rciu;1220  const variables = req.body.vars;1221  const leche = req.body.leche;1222  const yearsInterval = [];1223  const queryInitial = {1224    ANOCAT: { $gte: initialYear, $lte: finalYear },1225    edadgestacional: { $lt: 37 },1226  };1227  const query = manageFilters(queryInitial, variables);1228  const data = await medidasCrecimiento1229    .find(query)1230    .select([1231      "ANOCAT",1232      "RCIUpesoFenton",1233      "edadgestacionalalaentrada",1234      "alimentacion.sem40",1235      "peso.sem40",1236      "talla.sem40",1237      "pc.sem40",1238      "alimentacion.mes3",1239      "peso.mes3",1240      "talla.mes3",1241      "pc.mes3",1242      "alimentacion.mes6",1243      "peso.mes6",1244      "talla.mes6",1245      "pc.mes6",1246      "alimentacion.mes9",1247      "peso.mes9",1248      "talla.mes9",1249      "pc.mes9",1250      "alimentacion.mes12",1251      "peso.mes12",1252      "talla.mes12",1253      "pc.mes12",1254    ])1255    .lean();1256  for (let index = initialYear; index < parseInt(finalYear) + 1; index++) {1257    yearsInterval.push(index.toString());1258  }1259  const tiempo =1260    time == "40"1261      ? "sem40"1262      : time == "3"1263      ? "mes3"1264      : time == "6"1265      ? "mes6"1266      : time == "9"1267      ? "mes9"1268      : "mes12";1269  const dataParallel = [];1270  for (let i = 0; i < yearsInterval.length; i++) {1271    dataParallel.push({1272      año: yearsInterval[i],1273      EG:1274        Math.round(1275          (data1276            .filter(1277              (obj) =>1278                obj.ANOCAT == yearsInterval[i] &&1279                (rciu == "1"1280                  ? obj.RCIUpesoFenton == 11281                  : obj.RCIUpesoFenton == 0) &&1282                obj["edadgestacionalalaentrada"] &&1283                (leche == "true"1284                  ? time == "40"1285                    ? obj.alimentacion && obj.alimentacion.sem40 != 31286                    : time == "3"1287                    ? obj.alimentacion && obj.alimentacion.mes3 != 31288                    : time == "6"1289                    ? obj.alimentacion && obj.alimentacion.mes6 != 31290                    : time == "9"1291                    ? obj.alimentacion && obj.alimentacion.mes9 != 41292                    : obj.alimentacion && obj.alimentacion.mes12 != 31293                  : true)1294            )1295            .reduce((a, b) => a + (b["edadgestacionalalaentrada"] || 0), 0) /1296            data.filter(1297              (obj) =>1298                obj.ANOCAT == yearsInterval[i] &&1299                (rciu == "1"1300                  ? obj.RCIUpesoFenton == 11301                  : obj.RCIUpesoFenton == 0)1302            ).length) *1303            1001304        ) / 100,1305      "peso (gr)":1306        Math.round(1307          (data1308            .filter(1309              (obj) =>1310                obj.ANOCAT == yearsInterval[i] &&1311                (rciu == "1"1312                  ? obj.RCIUpesoFenton == 11313                  : obj.RCIUpesoFenton == 0) &&1314                obj["peso"] &&1315                (leche == "true"1316                  ? time == "40"1317                    ? obj.alimentacion && obj.alimentacion.sem40 != 31318                    : time == "3"1319                    ? obj.alimentacion && obj.alimentacion.mes3 != 31320                    : time == "6"1321                    ? obj.alimentacion && obj.alimentacion.mes6 != 31322                    : time == "9"1323                    ? obj.alimentacion && obj.alimentacion.mes9 != 41324                    : obj.alimentacion && obj.alimentacion.mes12 != 31325                  : true)1326            )1327            .reduce((a, b) => a + (b["peso"][tiempo] || 0), 0) /1328            data.filter(1329              (obj) =>1330                obj.ANOCAT == yearsInterval[i] &&1331                (rciu == "1"1332                  ? obj.RCIUpesoFenton == 11333                  : obj.RCIUpesoFenton == 0)1334            ).length) *1335            1001336        ) / 100,1337      "talla (cm)":1338        Math.round(1339          (data1340            .filter(1341              (obj) =>1342                obj.ANOCAT == yearsInterval[i] &&1343                (rciu == "1"1344                  ? obj.RCIUpesoFenton == 11345                  : obj.RCIUpesoFenton == 0) &&1346                obj["talla"] &&1347                (leche == "true"1348                  ? time == "40"1349                    ? obj.alimentacion && obj.alimentacion.sem40 != 31350                    : time == "3"1351                    ? obj.alimentacion && obj.alimentacion.mes3 != 31352                    : time == "6"1353                    ? obj.alimentacion && obj.alimentacion.mes6 != 31354                    : time == "9"1355                    ? obj.alimentacion && obj.alimentacion.mes9 != 41356                    : obj.alimentacion && obj.alimentacion.mes12 != 31357                  : true)1358            )1359            .reduce((a, b) => a + (b["talla"][tiempo] || 0), 0) /1360            data.filter(1361              (obj) =>1362                obj.ANOCAT == yearsInterval[i] &&1363                (rciu == "1"1364                  ? obj.RCIUpesoFenton == 11365                  : obj.RCIUpesoFenton == 0)1366            ).length) *1367            1001368        ) / 100,1369      "pc (cm)":1370        Math.round(1371          (data1372            .filter(1373              (obj) =>1374                obj.ANOCAT == yearsInterval[i] &&1375                (rciu == "1"1376                  ? obj.RCIUpesoFenton == 11377                  : obj.RCIUpesoFenton == 0) &&1378                obj["pc"] &&1379                (leche == "true"1380                  ? time == "40"1381                    ? obj.alimentacion && obj.alimentacion.sem40 != 31382                    : time == "3"1383                    ? obj.alimentacion && obj.alimentacion.mes3 != 31384                    : time == "6"1385                    ? obj.alimentacion && obj.alimentacion.mes6 != 31386                    : time == "9"1387                    ? obj.alimentacion && obj.alimentacion.mes9 != 41388                    : obj.alimentacion && obj.alimentacion.mes12 != 31389                  : true)1390            )1391            .reduce((a, b) => a + (b["pc"][tiempo] || 0), 0) /1392            data.filter(1393              (obj) =>1394                obj.ANOCAT == yearsInterval[i] &&1395                (rciu == "1"1396                  ? obj.RCIUpesoFenton == 11397                  : obj.RCIUpesoFenton == 0)1398            ).length) *1399            1001400        ) / 100,1401    });1402  }1403  handleResponse(dataParallel, res);1404});1405export const getEtapasCrecimiento = asyncHandler(async (req, res) => {1406  const etapas = [];1407  etapas.push({ value: "GENERALES", label: "Variables generales" });1408  etapas.push({ value: "PRIMER", label: "Primeros dÃas de vida" });1409  etapas.push({ value: "PMC", label: "Entrada Programa Canguro" });1410  etapas.push({ value: "SEM40", label: "40 Semanas" });1411  etapas.push({ value: "3M", label: "3 Meses" });1412  etapas.push({ value: "6M", label: "6 Meses" });1413  etapas.push({ value: "9M", label: "9 meses" });1414  etapas.push({ value: "12M", label: "12 Meses" });1415  handleResponse(etapas, res);1416});1417export const getVarsByEtapaCrecimiento = asyncHandler(async (req, res) => {1418  const etapa = req.body.etapa;1419  const vars = [];1420  if (etapa.includes("GENERALES")) {1421    vars.push({1422      value: "oftalmologiafinal",1423      label: "OftalmologÃa final",1424    });1425    vars.push({1426      value: "resoptometria",1427      label: "OptometrÃa",1428    });1429    vars.push({1430      value: "audiometria",1431      label: "AudiometrÃa",1432    });1433    vars.push({1434      value: "pesoAnio",1435      label: "Peso durante el primer año",1436    });1437    vars.push({1438      value: "tallaAnio",1439      label: "Talla durante el primer año",1440    });1441    vars.push({1442      value: "pcAnio",1443      label: "PerÃmetro craneal durante el primer año",1444    });1445  }1446  if (etapa.includes("PRIMER")) {1447    vars.push({1448      value: "TotalDiasHospitalizacion",1449      label: "DÃas hospitalización",1450    });1451    vars.push({1452      value: "UCI",1453      label: "UCI",1454    });1455  }1456  if (etapa.includes("PMC")) {1457    vars.push({1458      value: "edadgestacionalalaentrada",1459      label: "Edad gestacional entrada",1460    });1461    vars.push({1462      value: "edadgestasalPC",1463      label: "Edad gestacional salida",1464    });1465    vars.push({1466      value: "medidasEntrada",1467      label: "Medidas antropométricas entrada",1468    });1469    vars.push({1470      value: "pesoEntradaSalida",1471      label: "Peso entrada y salida (gr)",1472    });1473    vars.push({1474      value: "oxigenoentrada",1475      label: "OxÃgeno entrada",1476    });1477  }1478  if (etapa.includes("SEM40")) {1479    vars.push({1480      value: "alimentacion.sem40",1481      label: "Leche materna a las 40 semanas",1482    });1483    vars.push({1484      value: "medidasLecheSem40",1485      label: "Medidas antropométricas con leche materna (40 sem)",1486    });1487    vars.push({1488      value: "medidas40",1489      label: "Medidas antropométricas (40 sem)",1490    });1491    vars.push({1492      value: "peso.sem40",1493      label: "Peso 40 semanas",1494    });1495    vars.push({1496      value: "talla.sem40",1497      label: "Talla 40 semanas",1498    });1499    vars.push({1500      value: "pc.sem40",1501      label: "PerÃmetro craneal 40 semanas",1502    });1503    vars.push({1504      value: "nut4012",1505      label: "Nutrición 40 semanas - 12 meses",1506    });1507  }1508  if (etapa.includes("3M")) {1509    vars.push({1510      value: "alimentacion.mes3",1511      label: "Leche materna a los 3 meses",1512    });1513    vars.push({1514      value: "medidasLecheMes3",1515      label: "Medidas antropométricas con leche materna (mes 3)",1516    });1517    vars.push({1518      value: "medidas3",1519      label: "Medidas antropométricas (mes 3)",1520    });1521    vars.push({1522      value: "peso.mes3",1523      label: "Peso 3 meses",1524    });1525    vars.push({1526      value: "talla.mes3",1527      label: "Talla 3 meses",1528    });1529    vars.push({1530      value: "pc.mes3",1531      label: "PerÃmetro craneal 3 meses",1532    });1533    vars.push({1534      value: "Infanib3m",1535      label: "Infanib 3 meses",1536    });1537  }1538  if (etapa.includes("6M")) {1539    vars.push({1540      value: "alimentacion.mes6",1541      label: "Leche materna a los 6 meses",1542    });1543    vars.push({1544      value: "medidasLecheMes6",1545      label: "Medidas antropométricas con leche materna (mes 6)",1546    });1547    vars.push({1548      value: "medidas6",1549      label: "Medidas antropométricas (mes 6)",1550    });1551    vars.push({1552      value: "peso.mes6",1553      label: "Peso 6 meses",1554    });1555    vars.push({1556      value: "talla.mes6",1557      label: "Talla 6 meses",1558    });1559    vars.push({1560      value: "pc.mes6",1561      label: "PerÃmetro craneal 6 meses",1562    });1563    vars.push({1564      value: "Infanib6m",1565      label: "Infanib 6 meses",1566    });1567    vars.push({1568      value: "CD",1569      label: "Griffiths (coeficiente intelectual)",1570    });1571  }1572  if (etapa.includes("9M")) {1573    vars.push({1574      value: "alimentacion.mes9",1575      label: "Leche materna a los 9 meses",1576    });1577    vars.push({1578      value: "medidasLecheMes9",1579      label: "Medidas antropométricas con leche materna (mes 9)",1580    });1581    vars.push({1582      value: "medidas9",1583      label: "Medidas antropométricas (mes 9)",1584    });1585    vars.push({1586      value: "peso.mes9",1587      label: "Peso 9 meses",1588    });1589    vars.push({1590      value: "talla.mes9",1591      label: "Talla 9 meses",1592    });1593    vars.push({1594      value: "pc.mes9",1595      label: "PerÃmetro craneal 9 meses",1596    });1597    vars.push({1598      value: "Infanib9m",1599      label: "Infanib 9 meses",1600    });1601  }1602  if (etapa.includes("12M")) {1603    vars.push({1604      value: "alimentacion.mes12",1605      label: "Leche materna a los 12 meses",1606    });1607    vars.push({1608      value: "medidasLecheMes12",1609      label: "Medidas antropométricas con leche materna (mes 12)",1610    });1611    vars.push({1612      value: "medidas12",1613      label: "Medidas antropométricas (mes 12)",1614    });1615    vars.push({1616      value: "peso.mes12",1617      label: "Peso 12 meses",1618    });1619    vars.push({1620      value: "talla.mes12",1621      label: "Talla 12 meses",1622    });1623    vars.push({1624      value: "pc.mes12",1625      label: "PerÃmetro craneal 12 meses",1626    });1627    vars.push({1628      value: "nut4012",1629      label: "Nutrición 40 semanas - 12 meses",1630    });1631    vars.push({1632      value: "Infanib12m",1633      label: "Infanib 12 meses",1634    });1635    vars.push({1636      value: "CD",1637      label: "Griffiths (coeficiente intelectual)",1638    });1639  }1640  handleResponse(vars, res);1641});1642export const RCIUNut4012 = asyncHandler(async (req, res) => {1643  const initialYear = req.body.inicio;1644  const finalYear = req.body.fin;1645  const time = req.body.time;1646  const variables = req.body.vars;1647  const queryInitial = {1648    ANOCAT: { $gte: initialYear, $lte: finalYear },1649    edadgestacional: { $lt: 37 },1650  };1651  const query = manageFilters(queryInitial, variables);1652  const data = await medidasCrecimiento1653    .find(query)1654    .select([1655      "ANOCAT",1656      "RCIUpesoFenton",1657      time == "40" ? "Indexnutricion40sem" : "indexnutricion12meses",1658    ])1659    .lean();1660  const dataVis = {};1661  const dataWith = [];1662  const dataWithout = [];1663  const datasets = [];1664  dataWith.push(1665    Math.round(1666      (data.filter(1667        (obj) =>1668          obj.ANOCAT >= initialYear &&1669          obj.ANOCAT <= finalYear &&1670          obj.RCIUpesoFenton == 1 &&1671          (time == "40"1672            ? obj.Indexnutricion40sem == 01673            : obj.indexnutricion12meses == 0)1674      ).length /1675        data.filter(1676          (obj) =>1677            obj.ANOCAT >= initialYear &&1678            obj.ANOCAT <= finalYear &&1679            obj.RCIUpesoFenton == 11680        ).length) *1681        100 *1682        1001683    ) / 1001684  );1685  dataWith.push(1686    Math.round(1687      (data.filter(1688        (obj) =>1689          obj.ANOCAT >= initialYear &&1690          obj.ANOCAT <= finalYear &&1691          obj.RCIUpesoFenton == 1 &&1692          (time == "40"1693            ? obj.Indexnutricion40sem == 11694            : obj.indexnutricion12meses == 1)1695      ).length /1696        data.filter(1697          (obj) =>1698            obj.ANOCAT >= initialYear &&1699            obj.ANOCAT <= finalYear &&1700            obj.RCIUpesoFenton == 11701        ).length) *1702        100 *1703        1001704    ) / 1001705  );1706  dataWithout.push(1707    Math.round(1708      (data.filter(1709        (obj) =>1710          obj.ANOCAT >= initialYear &&1711          obj.ANOCAT <= finalYear &&1712          obj.RCIUpesoFenton == 0 &&1713          (time == "40"1714            ? obj.Indexnutricion40sem == 01715            : obj.indexnutricion12meses == 0)1716      ).length /1717        data.filter(1718          (obj) =>1719            obj.ANOCAT >= initialYear &&1720            obj.ANOCAT <= finalYear &&1721            obj.RCIUpesoFenton == 01722        ).length) *1723        100 *1724        1001725    ) / 1001726  );1727  dataWithout.push(1728    Math.round(1729      (data.filter(1730        (obj) =>1731          obj.ANOCAT >= initialYear &&1732          obj.ANOCAT <= finalYear &&1733          obj.RCIUpesoFenton == 0 &&1734          (time == "40"1735            ? obj.Indexnutricion40sem == 11736            : obj.indexnutricion12meses == 1)1737      ).length /1738        data.filter(1739          (obj) =>1740            obj.ANOCAT >= initialYear &&1741            obj.ANOCAT <= finalYear &&1742            obj.RCIUpesoFenton == 01743        ).length) *1744        100 *1745        1001746    ) / 1001747  );1748  datasets.push({1749    label: "con RCIU",1750    data: dataWith,1751    backgroundColor: time == "40" ? "#0E7FA6" : "#FF955B",1752  });1753  datasets.push({1754    label: "sin RCIU",1755    data: dataWithout,1756    backgroundColor: time == "40" ? "#70D6BC" : "#A6330A",1757  });1758  dataVis.labels = ["Disarmónico", "Armónico"];1759  dataVis.datasets = datasets;1760  handleResponse(dataVis, res);1761});1762export const getGriffiths = asyncHandler(async (req, res) => {1763  const initialYear = req.body.inicio;1764  const finalYear = req.body.fin;1765  const variables = req.body.vars;1766  const graph = req.body.graph;1767  const queryInitial = {1768    ANOCAT: { $gte: initialYear, $lte: finalYear },1769    edadgestacional: { $lt: 37 },1770  };1771  const query = manageFilters(queryInitial, variables);1772  const data = await medidasCrecimiento1773    .find(query)1774    .select([1775      "ANOCAT",1776      "RCIUpesoFenton",1777      "RCIUpesoFentonentrada",1778      "CD6",1779      "CD12",1780    ])1781    .lean();1782  const dataVis = {};1783  const dataSix = [];1784  const dataTwelve = [];1785  const datasets = [];1786  dataSix.push(1787    data.filter(1788      (obj) =>1789        obj.ANOCAT >= initialYear &&1790        obj.ANOCAT <= finalYear &&1791        (obj["CD6"] != null || obj["CD6"] != undefined || obj["CD6"] != NaN) &&1792        obj["CD6"] <= 69 &&1793        (graph == "1"1794          ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 11795          : graph == "2"1796          ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 01797          : obj.RCIUpesoFenton == 1)1798    ).length1799  );1800  dataSix.push(1801    data.filter(1802      (obj) =>1803        obj.ANOCAT >= initialYear &&1804        obj.ANOCAT <= finalYear &&1805        (obj["CD6"] != null || obj["CD6"] != undefined || obj["CD6"] != NaN) &&1806        obj.CD6 >= 70 &&1807        obj.CD6 <= 79 &&1808        (graph == "1"1809          ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 11810          : graph == "2"1811          ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 01812          : obj.RCIUpesoFenton == 1)1813    ).length1814  );1815  dataSix.push(1816    data.filter(1817      (obj) =>1818        obj.ANOCAT >= initialYear &&1819        obj.ANOCAT <= finalYear &&1820        (obj["CD6"] != null || obj["CD6"] != undefined || obj["CD6"] != NaN) &&1821        obj.CD6 >= 80 &&1822        obj.CD6 <= 89 &&1823        (graph == "1"1824          ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 11825          : graph == "2"1826          ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 01827          : obj.RCIUpesoFenton == 1)1828    ).length1829  );1830  dataSix.push(1831    data.filter(1832      (obj) =>1833        obj.ANOCAT >= initialYear &&1834        obj.ANOCAT <= finalYear &&1835        (obj["CD6"] != null || obj["CD6"] != undefined || obj["CD6"] != NaN) &&1836        obj.CD6 >= 90 &&1837        obj.CD6 <= 109 &&1838        (graph == "1"1839          ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 11840          : graph == "2"1841          ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 01842          : obj.RCIUpesoFenton == 1)1843    ).length1844  );1845  dataSix.push(1846    data.filter(1847      (obj) =>1848        obj.ANOCAT >= initialYear &&1849        obj.ANOCAT <= finalYear &&1850        (obj["CD6"] != null || obj["CD6"] != undefined || obj["CD6"] != NaN) &&1851        obj.CD6 >= 110 &&1852        obj.CD6 <= 119 &&1853        (graph == "1"1854          ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 11855          : graph == "2"1856          ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 01857          : obj.RCIUpesoFenton == 1)1858    ).length1859  );1860  dataSix.push(1861    data.filter(1862      (obj) =>1863        obj.ANOCAT >= initialYear &&1864        obj.ANOCAT <= finalYear &&1865        (obj["CD6"] != null || obj["CD6"] != undefined || obj["CD6"] != NaN) &&1866        obj.CD6 >= 120 &&1867        obj.CD6 <= 129 &&1868        (graph == "1"1869          ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 11870          : graph == "2"1871          ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 01872          : obj.RCIUpesoFenton == 1)1873    ).length1874  );1875  dataSix.push(1876    data.filter(1877      (obj) =>1878        obj.ANOCAT >= initialYear &&1879        obj.ANOCAT <= finalYear &&1880        (obj["CD6"] != null || obj["CD6"] != undefined || obj["CD6"] != NaN) &&1881        obj.CD6 >= 130 &&1882        (graph == "1"1883          ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 11884          : graph == "2"1885          ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 01886          : obj.RCIUpesoFenton == 1)1887    ).length1888  );1889  dataTwelve.push(1890    data.filter(1891      (obj) =>1892        obj.ANOCAT >= initialYear &&1893        obj.ANOCAT <= finalYear &&1894        (obj["CD12"] != null ||1895          obj["CD12"] != undefined ||1896          obj["CD12"] != NaN) &&1897        obj["CD12"] <= 69 &&1898        (graph == "1"1899          ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 11900          : graph == "2"1901          ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 01902          : obj.RCIUpesoFenton == 1)1903    ).length1904  );1905  dataTwelve.push(1906    data.filter(1907      (obj) =>1908        obj.ANOCAT >= initialYear &&1909        obj.ANOCAT <= finalYear &&1910        (obj["CD12"] != null ||1911          obj["CD12"] != undefined ||1912          obj["CD12"] != NaN) &&1913        obj["CD12"] >= 70 &&1914        obj["CD12"] <= 79 &&1915        (graph == "1"1916          ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 11917          : graph == "2"1918          ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 01919          : obj.RCIUpesoFenton == 1)1920    ).length1921  );1922  dataTwelve.push(1923    data.filter(1924      (obj) =>1925        obj.ANOCAT >= initialYear &&1926        obj.ANOCAT <= finalYear &&1927        (obj["CD12"] != null ||1928          obj["CD12"] != undefined ||1929          obj["CD12"] != NaN) &&1930        obj.CD12 >= 80 &&1931        obj.CD12 <= 89 &&1932        (graph == "1"1933          ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 11934          : graph == "2"1935          ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 01936          : obj.RCIUpesoFenton == 1)1937    ).length1938  );1939  dataTwelve.push(1940    data.filter(1941      (obj) =>1942        obj.ANOCAT >= initialYear &&1943        obj.ANOCAT <= finalYear &&1944        (obj["CD12"] != null ||1945          obj["CD12"] != undefined ||1946          obj["CD12"] != NaN) &&1947        obj.CD12 >= 90 &&1948        obj.CD12 <= 109 &&1949        (graph == "1"1950          ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 11951          : graph == "2"1952          ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 01953          : obj.RCIUpesoFenton == 1)1954    ).length1955  );1956  dataTwelve.push(1957    data.filter(1958      (obj) =>1959        obj.ANOCAT >= initialYear &&1960        obj.ANOCAT <= finalYear &&1961        (obj["CD12"] != null ||1962          obj["CD12"] != undefined ||1963          obj["CD12"] != NaN) &&1964        obj.CD12 >= 110 &&1965        obj.CD12 <= 119 &&1966        (graph == "1"1967          ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 11968          : graph == "2"1969          ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 01970          : obj.RCIUpesoFenton == 1)1971    ).length1972  );1973  dataTwelve.push(1974    data.filter(1975      (obj) =>1976        obj.ANOCAT >= initialYear &&1977        obj.ANOCAT <= finalYear &&1978        (obj["CD12"] != null ||1979          obj["CD12"] != undefined ||1980          obj["CD12"] != NaN) &&1981        obj.CD12 >= 120 &&1982        obj.CD12 <= 129 &&1983        (graph == "1"1984          ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 11985          : graph == "2"1986          ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 01987          : obj.RCIUpesoFenton == 1)1988    ).length1989  );1990  dataTwelve.push(1991    data.filter(1992      (obj) =>1993        obj.ANOCAT >= initialYear &&1994        obj.ANOCAT <= finalYear &&1995        (obj["CD12"] != null ||1996          obj["CD12"] != undefined ||1997          obj["CD12"] != NaN) &&1998        obj.CD12 >= 130 &&1999        (graph == "1"2000          ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 12001          : graph == "2"2002          ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 02003          : obj.RCIUpesoFenton == 1)2004    ).length2005  );2006  datasets.push({2007    label: "CD6",2008    data: dataSix,2009    backgroundColor:2010      graph == "1" ? "#0E7FA6" : graph == "2" ? "#70D6BC" : "#2DEB4D",2011  });2012  datasets.push({2013    label: "CD12",2014    data: dataTwelve,2015    backgroundColor:2016      graph == "1" ? "#FF955B" : graph == "2" ? "#A6330A" : "#F5C42F",2017  });2018  dataVis.labels = [2019    "<69",2020    "70-79",2021    "80-89",2022    "90-109",2023    "110-119",2024    "120-129",2025    ">130",2026  ];2027  dataVis.datasets = datasets;2028  handleResponse(dataVis, res);2029});2030export const RCIUInfanibProm = asyncHandler(async (req, res) => {2031  const initialYear = req.body.inicio;2032  const finalYear = req.body.fin;2033  const variables = req.body.vars;2034  const graph = req.body.graph;2035  const queryInitial = {2036    ANOCAT: { $gte: initialYear, $lte: finalYear },2037    edadgestacional: { $lt: 37 },2038  };2039  const query = manageFilters(queryInitial, variables);2040  const data = await medidasCrecimiento2041    .find(query)2042    .select([2043      "ANOCAT",2044      "RCIUpesoFenton",2045      "RCIUpesoFentonentrada",2046      "Infanib3m",2047      "Infanib6m",2048      "Infanib9m",2049      "Infanib12m",2050    ])2051    .lean();2052  const dataVis = {};2053  const dataPerdida = [];2054  const dataNormal = [];2055  const dataTrans = [];2056  const dataAnormal = [];2057  const datasets = [];2058  for (let i = 0; i < 4; i++) {2059    dataPerdida.push(2060      Math.round(2061        (data.filter(2062          (obj) =>2063            obj.ANOCAT >= initialYear &&2064            obj.ANOCAT <= finalYear &&2065            (i == 02066              ? obj.Infanib3m == null ||2067                obj.Infanib3m == undefined ||2068                obj.Infanib3m == NaN2069              : i == 12070              ? obj.Infanib6m == null ||2071                obj.Infanib6m == undefined ||2072                obj.Infanib6m == NaN2073              : i == 22074              ? obj.Infanib9m == null ||2075                obj.Infanib9m == undefined ||2076                obj.Infanib9m == NaN2077              : obj.Infanib12m == null ||2078                obj.Infanib12m == undefined ||2079                obj.Infanib12m == NaN) &&2080            (graph == "1"2081              ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 12082              : graph == "2"2083              ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 02084              : obj.RCIUpesoFenton == 1)2085        ).length /2086          data.filter(2087            (obj) =>2088              obj.ANOCAT >= initialYear &&2089              obj.ANOCAT <= finalYear &&2090              (graph == "1"2091                ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 12092                : graph == "2"2093                ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 02094                : obj.RCIUpesoFenton == 1)2095          ).length) *2096          100 *2097          1002098      ) / 1002099    );2100    dataNormal.push(2101      Math.round(2102        (data.filter(2103          (obj) =>2104            obj.ANOCAT >= initialYear &&2105            obj.ANOCAT <= finalYear &&2106            (i == 02107              ? obj.Infanib3m == 12108              : i == 12109              ? obj.Infanib6m == 12110              : i == 22111              ? obj.Infanib9m == 12112              : obj.Infanib12m == 1) &&2113            (graph == "1"2114              ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 12115              : graph == "2"2116              ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 02117              : obj.RCIUpesoFenton == 1)2118        ).length /2119          data.filter(2120            (obj) =>2121              obj.ANOCAT >= initialYear &&2122              obj.ANOCAT <= finalYear &&2123              (graph == "1"2124                ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 12125                : graph == "2"2126                ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 02127                : obj.RCIUpesoFenton == 1)2128          ).length) *2129          100 *2130          1002131      ) / 1002132    );2133    dataTrans.push(2134      Math.round(2135        (data.filter(2136          (obj) =>2137            obj.ANOCAT >= initialYear &&2138            obj.ANOCAT <= finalYear &&2139            (i == 02140              ? obj.Infanib3m == 22141              : i == 12142              ? obj.Infanib6m == 22143              : i == 22144              ? obj.Infanib9m == 22145              : obj.Infanib12m == 2) &&2146            (graph == "1"2147              ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 12148              : graph == "2"2149              ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 02150              : obj.RCIUpesoFenton == 1)2151        ).length /2152          data.filter(2153            (obj) =>2154              obj.ANOCAT >= initialYear &&2155              obj.ANOCAT <= finalYear &&2156              (graph == "1"2157                ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 12158                : graph == "2"2159                ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 02160                : obj.RCIUpesoFenton == 1)2161          ).length) *2162          100 *2163          1002164      ) / 1002165    );2166    dataAnormal.push(2167      Math.round(2168        (data.filter(2169          (obj) =>2170            obj.ANOCAT >= initialYear &&2171            obj.ANOCAT <= finalYear &&2172            (i == 02173              ? obj.Infanib3m == 32174              : i == 12175              ? obj.Infanib6m == 32176              : i == 22177              ? obj.Infanib9m == 32178              : obj.Infanib12m == 3) &&2179            (graph == "1"2180              ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 12181              : graph == "2"2182              ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 02183              : obj.RCIUpesoFenton == 1)2184        ).length /2185          data.filter(2186            (obj) =>2187              obj.ANOCAT >= initialYear &&2188              obj.ANOCAT <= finalYear &&2189              (graph == "1"2190                ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 12191                : graph == "2"2192                ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 02193                : obj.RCIUpesoFenton == 1)2194          ).length) *2195          100 *2196          1002197      ) / 1002198    );2199  }2200  datasets.push({2201    label: "Perdido",2202    data: dataPerdida,2203    backgroundColor: "#0E7FA6",2204  });2205  datasets.push({2206    label: "Normal",2207    data: dataNormal,2208    backgroundColor: "#FF955B",2209  });2210  datasets.push({2211    label: "Transitorio",2212    data: dataTrans,2213    backgroundColor: "#A6330A",2214  });2215  datasets.push({2216    label: "Anormal",2217    data: dataAnormal,2218    backgroundColor: "#F5C42F",2219  });2220  dataVis.labels = ["mes 3", "mes 6", "mes 9", "mes 12"];2221  dataVis.datasets = datasets;2222  handleResponse(dataVis, res);2223});2224export const RCIUInfanibTime = asyncHandler(async (req, res) => {2225  const initialYear = req.body.inicio;2226  const finalYear = req.body.fin;2227  const time = req.body.time;2228  const graph = req.body.graph;2229  const variables = req.body.vars;2230  const yearsInterval = [];2231  const queryInitial = {2232    ANOCAT: { $gte: initialYear, $lte: finalYear },2233    edadgestacional: { $lt: 37 },2234  };2235  const query = manageFilters(queryInitial, variables);2236  const data = await medidasCrecimiento2237    .find(query)2238    .select([2239      "ANOCAT",2240      "RCIUpesoFenton",2241      "RCIUpesoFentonentrada",2242      "Infanib3m",2243      "Infanib6m",2244      "Infanib9m",2245      "Infanib12m",2246    ])2247    .lean();2248  for (let index = initialYear; index < parseInt(finalYear) + 1; index++) {2249    yearsInterval.push(index.toString());2250  }2251  const dataPoints1 = [];2252  const dataPoints2 = [];2253  const dataPoints3 = [];2254  const dataPoints4 = [];2255  const dataVis = {};2256  dataVis.colorSet = "customColorSet";2257  dataVis.axisX = {2258    title: "Años",2259    titleFontFamily: "arial",2260    labelFontFamily: "arial",2261    titleFontStyle: "bold",2262    interval: 5,2263  };2264  dataVis.axisY = {2265    title: "Frecuencia resultado Infanib",2266    titleFontFamily: "arial",2267    labelFontFamily: "arial",2268    titleFontStyle: "bold",2269  };2270  dataVis.toolTip = {2271    fontFamily: "arial",2272  };2273  dataVis.zoomEnabled = true;2274  dataVis.zoomType = "xy";2275  for (let i = 0; i < yearsInterval.length; i++) {2276    dataPoints1.push({2277      x: i,2278      y:2279        Math.round(2280          (data.filter(2281            (obj) =>2282              obj.ANOCAT == yearsInterval[i] &&2283              (time == "3"2284                ? obj.Infanib3m == 12285                : time == "6"2286                ? obj.Infanib6m == 12287                : time == "9"2288                ? obj.Infanib9m == 12289                : obj.Infanib12m == 1) &&2290              (graph == "1"2291                ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 12292                : graph == "2"2293                ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 02294                : obj.RCIUpesoFenton == 1)2295          ).length /2296            data.filter(2297              (obj) =>2298                obj.ANOCAT == yearsInterval[i] &&2299                (graph == "1"2300                  ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 12301                  : graph == "2"2302                  ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 02303                  : obj.RCIUpesoFenton == 1)2304            ).length) *2305            100 *2306            1002307        ) / 100,2308    });2309    dataPoints2.push({2310      x: i,2311      y:2312        Math.round(2313          (data.filter(2314            (obj) =>2315              obj.ANOCAT == yearsInterval[i] &&2316              (time == "3"2317                ? obj.Infanib3m == 22318                : time == "6"2319                ? obj.Infanib6m == 22320                : time == "9"2321                ? obj.Infanib9m == 22322                : obj.Infanib12m == 2) &&2323              (graph == "1"2324                ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 12325                : graph == "2"2326                ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 02327                : obj.RCIUpesoFenton == 1)2328          ).length /2329            data.filter(2330              (obj) =>2331                obj.ANOCAT == yearsInterval[i] &&2332                (graph == "1"2333                  ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 12334                  : graph == "2"2335                  ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 02336                  : obj.RCIUpesoFenton == 1)2337            ).length) *2338            100 *2339            1002340        ) / 100,2341    });2342    dataPoints3.push({2343      x: i,2344      y:2345        Math.round(2346          (data.filter(2347            (obj) =>2348              obj.ANOCAT == yearsInterval[i] &&2349              (time == "3"2350                ? obj.Infanib3m == 32351                : time == "6"2352                ? obj.Infanib6m == 32353                : time == "9"2354                ? obj.Infanib9m == 32355                : obj.Infanib12m == 3) &&2356              (graph == "1"2357                ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 12358                : graph == "2"2359                ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 02360                : obj.RCIUpesoFenton == 1)2361          ).length /2362            data.filter(2363              (obj) =>2364                obj.ANOCAT == yearsInterval[i] &&2365                (graph == "1"2366                  ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 12367                  : graph == "2"2368                  ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 02369                  : obj.RCIUpesoFenton == 1)2370            ).length) *2371            100 *2372            1002373        ) / 100,2374    });2375    dataPoints4.push({2376      x: i,2377      y:2378        Math.round(2379          (data.filter(2380            (obj) =>2381              obj.ANOCAT == yearsInterval[i] &&2382              (time == "3"2383                ? obj.Infanib3m == null ||2384                  obj.Infanib3m == undefined ||2385                  obj.Infanib3m == NaN2386                : time == "6"2387                ? obj.Infanib6m == null ||2388                  obj.Infanib6m == undefined ||2389                  obj.Infanib6m == NaN2390                : time == "9"2391                ? obj.Infanib9m == null ||2392                  obj.Infanib9m == undefined ||2393                  obj.Infanib9m == NaN2394                : obj.Infanib12m == null ||2395                  obj.Infanib12m == undefined ||2396                  obj.Infanib12m == NaN) &&2397              (graph == "1"2398                ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 12399                : graph == "2"2400                ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 02401                : obj.RCIUpesoFenton == 1)2402          ).length /2403            data.filter(2404              (obj) =>2405                obj.ANOCAT == yearsInterval[i] &&2406                (graph == "1"2407                  ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 12408                  : graph == "2"2409                  ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 02410                  : obj.RCIUpesoFenton == 1)2411            ).length) *2412            100 *2413            1002414        ) / 100,2415    });2416  }2417  dataVis.data = [];2418  dataVis.height = 300;2419  dataVis.legend = {2420    horizontalAlign: "top",2421    verticalAlign: "top",2422    fontFamily: "arial",2423  };2424  dataVis.data.push({2425    type: "spline",2426    markerSize: 5,2427    connectNullData: true,2428    name: "Normal",2429    showInLegend: true,2430    dataPoints: dataPoints1,2431  });2432  dataVis.data.push({2433    type: "spline",2434    markerSize: 5,2435    connectNullData: true,2436    name: "Transitorio",2437    showInLegend: true,2438    dataPoints: dataPoints2,2439  });2440  dataVis.data.push({2441    type: "spline",2442    markerSize: 5,2443    connectNullData: true,2444    name: "Anormal",2445    showInLegend: true,2446    dataPoints: dataPoints3,2447  });2448  dataVis.data.push({2449    type: "spline",2450    markerSize: 5,2451    connectNullData: true,2452    name: "VacÃos",2453    showInLegend: true,2454    dataPoints: dataPoints4,2455  });2456  handleResponse(dataVis, res);2457});2458export const RCIUoftalmologia = asyncHandler(async (req, res) => {2459  const initialYear = req.body.inicio;2460  const finalYear = req.body.fin;2461  const variables = req.body.vars;2462  const graph = req.body.graph;2463  const queryInitial = {2464    ANOCAT: { $gte: initialYear, $lte: finalYear },2465    edadgestacional: { $lt: 37 },2466  };2467  const query = manageFilters(queryInitial, variables);2468  const data = await medidasCrecimiento2469    .find(query)2470    .select([2471      "ANOCAT",2472      "RCIUpesoFenton",2473      "RCIUpesoFentonentrada",2474      "oftalmologiafinal",2475    ])2476    .lean();2477  const dataVis = {};2478  const datos = [];2479  const datasets = [];2480  for (let i = 0; i < 7; i++) {2481    datos.push(2482      Math.round(2483        (data.filter(2484          (obj) =>2485            obj.ANOCAT >= initialYear &&2486            obj.ANOCAT <= finalYear &&2487            (i == 02488              ? obj.oftalmologiafinal == 02489              : i == 12490              ? obj.oftalmologiafinal == 12491              : i == 22492              ? obj.oftalmologiafinal == 22493              : i == 32494              ? obj.oftalmologiafinal == 32495              : i == 42496              ? obj.oftalmologiafinal == 62497              : obj.oftalmologiafinal == 10) &&2498            (graph == "1"2499              ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 12500              : graph == "2"2501              ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 02502              : obj.RCIUpesoFenton == 1)2503        ).length /2504          data.filter(2505            (obj) =>2506              obj.ANOCAT >= initialYear &&2507              obj.ANOCAT <= finalYear &&2508              (graph == "1"2509                ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 12510                : graph == "2"2511                ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 02512                : obj.RCIUpesoFenton == 1)2513          ).length) *2514          100 *2515          1002516      ) / 1002517    );2518  }2519  datasets.push({2520    label: "Resultados optometrÃa",2521    data: datos,2522    backgroundColor:2523      graph == "1" ? "#0E7FA6" : graph == "2" ? "#FF955B" : "#70D6BC",2524  });2525  dataVis.labels = [2526    "Espera consulta",2527    "ROP cualquier grado",2528    "No ROP",2529    "CirugÃa ocular",2530    "Ciegos",2531    "Otro diagnóstico",2532  ];2533  dataVis.datasets = datasets;2534  handleResponse(dataVis, res);2535});2536export const RCIUoptometria = asyncHandler(async (req, res) => {2537  const initialYear = req.body.inicio;2538  const finalYear = req.body.fin;2539  const variables = req.body.vars;2540  const graph = req.body.graph;2541  const queryInitial = {2542    ANOCAT: { $gte: initialYear, $lte: finalYear },2543    edadgestacional: { $lt: 37 },2544  };2545  const query = manageFilters(queryInitial, variables);2546  const data = await medidasCrecimiento2547    .find(query)2548    .select([2549      "ANOCAT",2550      "RCIUpesoFenton",2551      "RCIUpesoFentonentrada",2552      "resoptometria",2553    ])2554    .lean();2555  const dataVis = {};2556  const datos = [];2557  const datasets = [];2558  for (let i = 1; i < 6; i++) {2559    datos.push(2560      Math.round(2561        (data.filter(2562          (obj) =>2563            obj.ANOCAT >= initialYear &&2564            obj.ANOCAT <= finalYear &&2565            (i == 12566              ? obj.resoptometria == 12567              : i == 22568              ? obj.resoptometria == 22569              : i == 32570              ? obj.resoptometria == 32571              : i == 42572              ? obj.resoptometria == 42573              : obj.resoptometria == 7) &&2574            (graph == "1"2575              ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 12576              : graph == "2"2577              ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 02578              : obj.RCIUpesoFenton == 1)2579        ).length /2580          data.filter(2581            (obj) =>2582              obj.ANOCAT >= initialYear &&2583              obj.ANOCAT <= finalYear &&2584              (graph == "1"2585                ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 12586                : graph == "2"2587                ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 02588                : obj.RCIUpesoFenton == 1)2589          ).length) *2590          100 *2591          1002592      ) / 1002593    );2594  }2595  datasets.push({2596    label: "Resultados resoptometrÃa",2597    data: datos,2598    backgroundColor:2599      graph == "1" ? "#0E7FA6" : graph == "2" ? "#FF955B" : "#70D6BC",2600  });2601  dataVis.labels = [2602    "Normal",2603    "Miope",2604    "Astigmatismo",2605    "Hipermetropia",2606    "Otro diagnóstico",2607  ];2608  dataVis.datasets = datasets;2609  handleResponse(dataVis, res);2610});2611export const RCIUaudiometria = asyncHandler(async (req, res) => {2612  const initialYear = req.body.inicio;2613  const finalYear = req.body.fin;2614  const variables = req.body.vars;2615  const graph = req.body.graph;2616  const queryInitial = {2617    ANOCAT: { $gte: initialYear, $lte: finalYear },2618    edadgestacional: { $lt: 37 },2619  };2620  const query = manageFilters(queryInitial, variables);2621  const data = await medidasCrecimiento2622    .find(query)2623    .select([2624      "ANOCAT",2625      "RCIUpesoFenton",2626      "RCIUpesoFentonentrada",2627      "audiometria",2628    ])2629    .lean();2630  const dataVis = {};2631  const datos = [];2632  const datasets = [];2633  for (let i = 0; i < 3; i++) {2634    datos.push(2635      Math.round(2636        (data.filter(2637          (obj) =>2638            obj.ANOCAT >= initialYear &&2639            obj.ANOCAT <= finalYear &&2640            (i == 12641              ? obj.audiometria == -12642              : i == 22643              ? obj.audiometria == 02644              : obj.audiometria == 1) &&2645            (graph == "1"2646              ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 12647              : graph == "2"2648              ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 02649              : obj.RCIUpesoFenton == 1)2650        ).length /2651          data.filter(2652            (obj) =>2653              obj.ANOCAT >= initialYear &&2654              obj.ANOCAT <= finalYear &&2655              (graph == "1"2656                ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 12657                : graph == "2"2658                ? obj.RCIUpesoFenton == 0 && obj.RCIUpesoFentonentrada == 02659                : obj.RCIUpesoFenton == 1)2660          ).length) *2661          100 *2662          1002663      ) / 1002664    );2665  }2666  datasets.push({2667    label: "Resultados audiometrÃa",2668    data: datos,2669    backgroundColor:2670      graph == "1" ? "#0E7FA6" : graph == "2" ? "#FF955B" : "#70D6BC",2671  });2672  dataVis.labels = ["Muere o deserta", "Normal", "Anormal uno o dos lados"];2673  dataVis.datasets = datasets;2674  handleResponse(dataVis, res);2675});2676// RCIUAFPromMedidaBebeNacer2677export const RCIUPromMedidasGrowth = asyncHandler(async (req, res) => {2678  const variable = req.body.var;2679  const initialYear = req.body.inicio;2680  const finalYear = req.body.fin;2681  const yearsInterval = [];2682  const variables = req.body.vars;2683  // const desde = req.body.desde;2684  // const hasta = req.body.hasta;2685  const queryInitial = {2686    ANOCAT: { $gte: initialYear, $lte: finalYear },2687    edadgestacional: { $lt: 37 },2688  };2689  const query = manageFilters(queryInitial, variables);2690  // if (desde && desde != "0" && hasta && hasta != "0") {2691  //   if (variable == "pesoalnacer") {2692  //     query.pesoalnacer = { $gte: parseInt(desde), $lte: parseInt(hasta) };2693  //   } else if (variable == "tallaalnacer") {2694  //     query.tallaalnacer = { $gte: parseInt(desde), $lte: parseInt(hasta) };2695  //   } else if (variable == "pcalnacer") {2696  //     query.pcalnacer = { $gte: parseInt(desde), $lte: parseInt(hasta) };2697  //   }2698  // }2699  const data = await medidasCrecimiento2700    .find(query)2701    .select(["ANOCAT", "RCIUpesoFenton", variable])2702    .lean();2703  for (let index = initialYear; index < parseInt(finalYear) + 1; index++) {2704    yearsInterval.push(index.toString());2705  }2706  const dataVis = {};2707  const dataWith = [];2708  const dataWithout = [];2709  const datasets = [];2710  var split = variable.split(".");2711  var first = split[0];2712  var second = split[1];2713  for (let i = 0; i < yearsInterval.length; i++) {2714    dataWith.push(2715      Math.round(2716        (data2717          .filter(2718            (obj) =>2719              obj.RCIUpesoFenton == 1 &&2720              obj.ANOCAT == yearsInterval[i] &&2721              obj[first]2722          )2723          .reduce((a, b) => a + (b[first][second] || 0), 0) /2724          data.filter(2725            (obj) => obj.RCIUpesoFenton == 1 && obj.ANOCAT == yearsInterval[i]2726          ).length) *2727          1002728      ) / 1002729    );2730    dataWithout.push(2731      Math.round(2732        (data2733          .filter(2734            (obj) =>2735              obj.RCIUpesoFenton == 0 &&2736              obj.ANOCAT == yearsInterval[i] &&2737              obj[first]2738          )2739          .reduce((a, b) => a + (b[first][second] || 0), 0) /2740          data.filter(2741            (obj) => obj.RCIUpesoFenton == 0 && obj.ANOCAT == yearsInterval[i]2742          ).length) *2743          1002744      ) / 1002745    );2746  }2747  var medida = "";2748  if (variable.includes("peso")) {2749    medida = "(gr)";2750  } else if (variable.includes("talla") || variable.includes("pc")) {2751    medida = "(cm)";2752  }2753  datasets.push({2754    label: `Promedio ${variable} con RCIU ${medida}`,2755    data: dataWith,2756    backgroundColor: "#0E7FA6",2757  });2758  datasets.push({2759    label: `Promedio ${variable} sin RCIU ${medida}`,2760    data: dataWithout,2761    backgroundColor: "#FF955B",2762  });2763  dataVis.labels = yearsInterval;2764  dataVis.datasets = datasets;2765  handleResponse(dataVis, res);2766});2767export const RCIUMedidaAnio = asyncHandler(async (req, res) => {2768  const initialYear = req.body.inicio;2769  const finalYear = req.body.fin;2770  const variables = req.body.vars;2771  const variable = req.body.var;2772  const queryInitial = {2773    ANOCAT: { $gte: initialYear, $lte: finalYear },2774    edadgestacional: { $lt: 37 },2775  };2776  const query = manageFilters(queryInitial, variables);2777  const data = await medidasCrecimiento2778    .find(query)2779    .select(["ANOCAT", "RCIUpesoFenton", variable])2780    .lean();2781  const dataPoints1 = [];2782  const dataPoints2 = [];2783  const dataVis = {};2784  dataVis.colorSet = "customColorSetPrem";2785  dataVis.axisX = {2786    title: "Momento del año de vida",2787    titleFontFamily: "arial",2788    labelFontFamily: "arial",2789    titleFontStyle: "bold",2790    interval: 1,2791  };2792  dataVis.axisY = {2793    title: `Promedio ${variable}`,2794    titleFontFamily: "arial",2795    labelFontFamily: "arial",2796    titleFontStyle: "bold",2797  };2798  dataVis.toolTip = {2799    fontFamily: "arial",2800  };2801  dataVis.zoomEnabled = true;2802  dataVis.zoomType = "xy";2803  for (let i = 0; i < 5; i++) {2804    dataPoints1.push({2805      x: i,2806      y:2807        Math.round(2808          (data2809            .filter(2810              (obj) =>2811                obj.ANOCAT >= initialYear &&2812                obj.ANOCAT <= finalYear &&2813                obj[variable] &&2814                obj.RCIUpesoFenton == 12815            )2816            .reduce(2817              (a, b) =>2818                a +2819                (b[variable][2820                  i == 02821                    ? "sem40"2822                    : i == 12823                    ? "mes3"2824                    : i == 22825                    ? "mes6"2826                    : i == 32827                    ? "mes9"2828                    : "mes12"2829                ] || 0),2830              02831            ) /2832            data.filter(2833              (obj) =>2834                obj.ANOCAT >= initialYear &&2835                obj.ANOCAT <= finalYear &&2836                obj.RCIUpesoFenton == 12837            ).length) *2838            1002839        ) / 100,2840    });2841    dataPoints2.push({2842      x: i,2843      y:2844        Math.round(2845          (data2846            .filter(2847              (obj) =>2848                obj.ANOCAT >= initialYear &&2849                obj.ANOCAT <= finalYear &&2850                obj[variable] &&2851                obj.RCIUpesoFenton == 02852            )2853            .reduce(2854              (a, b) =>2855                a +2856                (b[variable][2857                  i == 02858                    ? "sem40"2859                    : i == 12860                    ? "mes3"2861                    : i == 22862                    ? "mes6"2863                    : i == 32864                    ? "mes9"2865                    : "mes12"2866                ] || 0),2867              02868            ) /2869            data.filter(2870              (obj) =>2871                obj.ANOCAT >= initialYear &&2872                obj.ANOCAT <= finalYear &&2873                obj.RCIUpesoFenton == 02874            ).length) *2875            1002876        ) / 100,2877    });2878  }2879  dataVis.data = [];2880  dataVis.height = 300;2881  dataVis.legend = {2882    horizontalAlign: "top",2883    verticalAlign: "top",2884    fontFamily: "arial",2885  };2886  dataVis.data.push({2887    type: "spline",2888    markerSize: 5,2889    connectNullData: true,2890    name: "con RCIU",2891    showInLegend: true,2892    dataPoints: dataPoints1,2893  });2894  dataVis.data.push({2895    type: "spline",2896    markerSize: 5,2897    connectNullData: true,2898    name: "sin RCIU",2899    showInLegend: true,2900    dataPoints: dataPoints2,2901  });2902  handleResponse(dataVis, res);...test_config.py
Source:test_config.py  
1#    Copyright (C) 2012 Red Hat, Inc.2#3#    Licensed under the Apache License, Version 2.0 (the "License"); you may4#    not use this file except in compliance with the License. You may obtain5#    a copy of the License at6#7#         http://www.apache.org/licenses/LICENSE-2.08#9#    Unless required by applicable law or agreed to in writing, software10#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT11#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the12#    License for the specific language governing permissions and limitations13#    under the License.14from lxml import etree15from nova.compute import arch16from nova.openstack.common import units17from nova import test18from nova.tests import matchers19from nova.virt.libvirt import config20class LibvirtConfigBaseTest(test.NoDBTestCase):21    def assertXmlEqual(self, expectedXmlstr, actualXmlstr):22        self.assertThat(actualXmlstr, matchers.XMLMatches(expectedXmlstr))23class LibvirtConfigTest(LibvirtConfigBaseTest):24    def test_config_plain(self):25        obj = config.LibvirtConfigObject(root_name="demo")26        xml = obj.to_xml()27        self.assertXmlEqual(xml, "<demo/>")28    def test_config_ns(self):29        obj = config.LibvirtConfigObject(root_name="demo", ns_prefix="foo",30                                         ns_uri="http://example.com/foo")31        xml = obj.to_xml()32        self.assertXmlEqual(xml, """33            <foo:demo xmlns:foo="http://example.com/foo"/>""")34    def test_config_text(self):35        obj = config.LibvirtConfigObject(root_name="demo")36        root = obj.format_dom()37        root.append(obj._text_node("foo", "bar"))38        xml = etree.tostring(root)39        self.assertXmlEqual(xml, "<demo><foo>bar</foo></demo>")40    def test_config_parse(self):41        inxml = "<demo><foo/></demo>"42        obj = config.LibvirtConfigObject(root_name="demo")43        obj.parse_str(inxml)44class LibvirtConfigCapsTest(LibvirtConfigBaseTest):45    def test_config_host(self):46        xmlin = """47        <capabilities>48          <host>49            <uuid>c7a5fdbd-edaf-9455-926a-d65c16db1809</uuid>50            <cpu>51              <arch>x86_64</arch>52              <model>Opteron_G3</model>53              <vendor>AMD</vendor>54              <topology sockets='1' cores='4' threads='1'/>55              <feature name='ibs'/>56              <feature name='osvw'/>57            </cpu>58            <topology>59              <cells num='2'>60                <cell id='0'>61                  <memory unit='KiB'>4048280</memory>62                  <cpus num='4'>63                    <cpu id='0' socket_id='0' core_id='0' siblings='0'/>64                    <cpu id='1' socket_id='0' core_id='1' siblings='1'/>65                    <cpu id='2' socket_id='0' core_id='2' siblings='2'/>66                    <cpu id='3' socket_id='0' core_id='3' siblings='3'/>67                  </cpus>68                </cell>69                <cell id='1'>70                  <memory unit='KiB'>4127684</memory>71                  <cpus num='4'>72                    <cpu id='4' socket_id='1' core_id='0' siblings='4'/>73                    <cpu id='5' socket_id='1' core_id='1' siblings='5'/>74                    <cpu id='6' socket_id='1' core_id='2' siblings='6'/>75                    <cpu id='7' socket_id='1' core_id='3' siblings='7'/>76                  </cpus>77                </cell>78              </cells>79            </topology>80          </host>81          <guest>82            <os_type>hvm</os_type>83            <arch name='x86_64'/>84          </guest>85          <guest>86            <os_type>hvm</os_type>87            <arch name='i686'/>88          </guest>89        </capabilities>"""90        obj = config.LibvirtConfigCaps()91        obj.parse_str(xmlin)92        self.assertIsInstance(obj.host, config.LibvirtConfigCapsHost)93        self.assertEqual(obj.host.uuid, "c7a5fdbd-edaf-9455-926a-d65c16db1809")94        xmlout = obj.to_xml()95        self.assertXmlEqual(xmlin, xmlout)96class LibvirtConfigGuestTimerTest(LibvirtConfigBaseTest):97    def test_config_platform(self):98        obj = config.LibvirtConfigGuestTimer()99        obj.track = "host"100        xml = obj.to_xml()101        self.assertXmlEqual(xml, """102            <timer name="platform" track="host"/>103        """)104    def test_config_pit(self):105        obj = config.LibvirtConfigGuestTimer()106        obj.name = "pit"107        obj.tickpolicy = "discard"108        xml = obj.to_xml()109        self.assertXmlEqual(xml, """110            <timer name="pit" tickpolicy="discard"/>111        """)112    def test_config_hpet(self):113        obj = config.LibvirtConfigGuestTimer()114        obj.name = "hpet"115        obj.present = False116        xml = obj.to_xml()117        self.assertXmlEqual(xml, """118            <timer name="hpet" present="no"/>119        """)120class LibvirtConfigGuestClockTest(LibvirtConfigBaseTest):121    def test_config_utc(self):122        obj = config.LibvirtConfigGuestClock()123        xml = obj.to_xml()124        self.assertXmlEqual(xml, """125            <clock offset="utc"/>126        """)127    def test_config_localtime(self):128        obj = config.LibvirtConfigGuestClock()129        obj.offset = "localtime"130        xml = obj.to_xml()131        self.assertXmlEqual(xml, """132            <clock offset="localtime"/>133        """)134    def test_config_timezone(self):135        obj = config.LibvirtConfigGuestClock()136        obj.offset = "timezone"137        obj.timezone = "EDT"138        xml = obj.to_xml()139        self.assertXmlEqual(xml, """140            <clock offset="timezone" timezone="EDT"/>141        """)142    def test_config_variable(self):143        obj = config.LibvirtConfigGuestClock()144        obj.offset = "variable"145        obj.adjustment = "123456"146        xml = obj.to_xml()147        self.assertXmlEqual(xml, """148            <clock offset="variable" adjustment="123456"/>149        """)150    def test_config_timers(self):151        obj = config.LibvirtConfigGuestClock()152        tmpit = config.LibvirtConfigGuestTimer()153        tmpit.name = "pit"154        tmpit.tickpolicy = "discard"155        tmrtc = config.LibvirtConfigGuestTimer()156        tmrtc.name = "rtc"157        tmrtc.tickpolicy = "merge"158        obj.add_timer(tmpit)159        obj.add_timer(tmrtc)160        xml = obj.to_xml()161        self.assertXmlEqual(xml, """162            <clock offset="utc">163               <timer name="pit" tickpolicy="discard"/>164               <timer name="rtc" tickpolicy="merge"/>165            </clock>166        """)167class LibvirtConfigCPUFeatureTest(LibvirtConfigBaseTest):168    def test_config_simple(self):169        obj = config.LibvirtConfigCPUFeature("mtrr")170        xml = obj.to_xml()171        self.assertXmlEqual(xml, """172            <feature name="mtrr"/>173        """)174class LibvirtConfigGuestCPUFeatureTest(LibvirtConfigBaseTest):175    def test_config_simple(self):176        obj = config.LibvirtConfigGuestCPUFeature("mtrr")177        obj.policy = "force"178        xml = obj.to_xml()179        self.assertXmlEqual(xml, """180            <feature name="mtrr" policy="force"/>181        """)182class LibvirtConfigGuestCPUNUMATest(LibvirtConfigBaseTest):183    def test_config_simple(self):184        obj = config.LibvirtConfigGuestCPUNUMA()185        cell = config.LibvirtConfigGuestCPUNUMACell()186        cell.id = 0187        cell.cpus = set([0, 1])188        cell.memory = 1000000189        obj.cells.append(cell)190        cell = config.LibvirtConfigGuestCPUNUMACell()191        cell.id = 1192        cell.cpus = set([2, 3])193        cell.memory = 1500000194        obj.cells.append(cell)195        xml = obj.to_xml()196        self.assertXmlEqual(xml, """197            <numa>198              <cell id="0" cpus="0-1" memory="1000000"/>199              <cell id="1" cpus="2-3" memory="1500000"/>200            </numa>201        """)202class LibvirtConfigCPUTest(LibvirtConfigBaseTest):203    def test_config_simple(self):204        obj = config.LibvirtConfigCPU()205        obj.model = "Penryn"206        xml = obj.to_xml()207        self.assertXmlEqual(xml, """208            <cpu>209              <model>Penryn</model>210            </cpu>211        """)212    def test_config_complex(self):213        obj = config.LibvirtConfigCPU()214        obj.model = "Penryn"215        obj.vendor = "Intel"216        obj.arch = arch.X86_64217        obj.add_feature(config.LibvirtConfigCPUFeature("mtrr"))218        obj.add_feature(config.LibvirtConfigCPUFeature("apic"))219        xml = obj.to_xml()220        self.assertXmlEqual(xml, """221            <cpu>222              <arch>x86_64</arch>223              <model>Penryn</model>224              <vendor>Intel</vendor>225              <feature name="apic"/>226              <feature name="mtrr"/>227            </cpu>228        """)229    def test_only_uniq_cpu_featues(self):230        obj = config.LibvirtConfigCPU()231        obj.model = "Penryn"232        obj.vendor = "Intel"233        obj.arch = arch.X86_64234        obj.add_feature(config.LibvirtConfigCPUFeature("mtrr"))235        obj.add_feature(config.LibvirtConfigCPUFeature("apic"))236        obj.add_feature(config.LibvirtConfigCPUFeature("apic"))237        obj.add_feature(config.LibvirtConfigCPUFeature("mtrr"))238        xml = obj.to_xml()239        self.assertXmlEqual(xml, """240            <cpu>241              <arch>x86_64</arch>242              <model>Penryn</model>243              <vendor>Intel</vendor>244              <feature name="apic"/>245              <feature name="mtrr"/>246            </cpu>247        """)248    def test_config_topology(self):249        obj = config.LibvirtConfigCPU()250        obj.model = "Penryn"251        obj.sockets = 4252        obj.cores = 4253        obj.threads = 2254        xml = obj.to_xml()255        self.assertXmlEqual(xml, """256            <cpu>257              <model>Penryn</model>258              <topology sockets="4" cores="4" threads="2"/>259            </cpu>260        """)261class LibvirtConfigGuestCPUTest(LibvirtConfigBaseTest):262    def test_config_simple(self):263        obj = config.LibvirtConfigGuestCPU()264        obj.model = "Penryn"265        xml = obj.to_xml()266        self.assertXmlEqual(xml, """267            <cpu match="exact">268              <model>Penryn</model>269            </cpu>270        """)271    def test_config_complex(self):272        obj = config.LibvirtConfigGuestCPU()273        obj.model = "Penryn"274        obj.vendor = "Intel"275        obj.arch = arch.X86_64276        obj.mode = "custom"277        obj.add_feature(config.LibvirtConfigGuestCPUFeature("mtrr"))278        obj.add_feature(config.LibvirtConfigGuestCPUFeature("apic"))279        xml = obj.to_xml()280        self.assertXmlEqual(xml, """281            <cpu mode="custom" match="exact">282              <arch>x86_64</arch>283              <model>Penryn</model>284              <vendor>Intel</vendor>285              <feature name="apic" policy="require"/>286              <feature name="mtrr" policy="require"/>287            </cpu>288        """)289    def test_config_host(self):290        obj = config.LibvirtConfigGuestCPU()291        obj.mode = "host-model"292        obj.match = "exact"293        xml = obj.to_xml()294        self.assertXmlEqual(xml, """295            <cpu mode="host-model" match="exact"/>296        """)297    def test_config_host_with_numa(self):298        obj = config.LibvirtConfigGuestCPU()299        obj.mode = "host-model"300        obj.match = "exact"301        numa = config.LibvirtConfigGuestCPUNUMA()302        cell = config.LibvirtConfigGuestCPUNUMACell()303        cell.id = 0304        cell.cpus = set([0, 1])305        cell.memory = 1000000306        numa.cells.append(cell)307        cell = config.LibvirtConfigGuestCPUNUMACell()308        cell.id = 1309        cell.cpus = set([2, 3])310        cell.memory = 1500000311        numa.cells.append(cell)312        obj.numa = numa313        xml = obj.to_xml()314        self.assertXmlEqual(xml, """315            <cpu mode="host-model" match="exact">316              <numa>317                <cell id="0" cpus="0-1" memory="1000000"/>318                <cell id="1" cpus="2-3" memory="1500000"/>319              </numa>320            </cpu>321        """)322class LibvirtConfigGuestSMBIOSTest(LibvirtConfigBaseTest):323    def test_config_simple(self):324        obj = config.LibvirtConfigGuestSMBIOS()325        xml = obj.to_xml()326        self.assertXmlEqual(xml, """327            <smbios mode="sysinfo"/>328        """)329class LibvirtConfigGuestSysinfoTest(LibvirtConfigBaseTest):330    def test_config_simple(self):331        obj = config.LibvirtConfigGuestSysinfo()332        xml = obj.to_xml()333        self.assertXmlEqual(xml, """334            <sysinfo type="smbios"/>335        """)336    def test_config_bios(self):337        obj = config.LibvirtConfigGuestSysinfo()338        obj.bios_vendor = "Acme"339        obj.bios_version = "6.6.6"340        xml = obj.to_xml()341        self.assertXmlEqual(xml, """342            <sysinfo type="smbios">343              <bios>344                <entry name="vendor">Acme</entry>345                <entry name="version">6.6.6</entry>346              </bios>347            </sysinfo>348        """)349    def test_config_system(self):350        obj = config.LibvirtConfigGuestSysinfo()351        obj.system_manufacturer = "Acme"352        obj.system_product = "Wile Coyote"353        obj.system_version = "6.6.6"354        obj.system_serial = "123456"355        obj.system_uuid = "c7a5fdbd-edaf-9455-926a-d65c16db1809"356        xml = obj.to_xml()357        self.assertXmlEqual(xml, """358            <sysinfo type="smbios">359              <system>360                <entry name="manufacturer">Acme</entry>361                <entry name="product">Wile Coyote</entry>362                <entry name="version">6.6.6</entry>363                <entry name="serial">123456</entry>364                <entry name="uuid">c7a5fdbd-edaf-9455-926a-d65c16db1809</entry>365              </system>366            </sysinfo>367        """)368    def test_config_mixed(self):369        obj = config.LibvirtConfigGuestSysinfo()370        obj.bios_vendor = "Acme"371        obj.system_manufacturer = "Acme"372        obj.system_product = "Wile Coyote"373        obj.system_uuid = "c7a5fdbd-edaf-9455-926a-d65c16db1809"374        xml = obj.to_xml()375        self.assertXmlEqual(xml, """376            <sysinfo type="smbios">377              <bios>378                <entry name="vendor">Acme</entry>379              </bios>380              <system>381                <entry name="manufacturer">Acme</entry>382                <entry name="product">Wile Coyote</entry>383                <entry name="uuid">c7a5fdbd-edaf-9455-926a-d65c16db1809</entry>384              </system>385            </sysinfo>386        """)387class LibvirtConfigGuestDiskTest(LibvirtConfigBaseTest):388    def test_config_file(self):389        obj = config.LibvirtConfigGuestDisk()390        obj.source_type = "file"391        obj.source_path = "/tmp/hello"392        obj.target_dev = "/dev/hda"393        obj.target_bus = "ide"394        xml = obj.to_xml()395        self.assertXmlEqual(xml, """396            <disk type="file" device="disk">397              <source file="/tmp/hello"/>398              <target bus="ide" dev="/dev/hda"/>399            </disk>""")400    def test_config_file_parse(self):401        xml = """<disk type="file" device="disk">402                   <source file="/tmp/hello"/>403                   <target bus="ide" dev="/dev/hda"/>404                 </disk>"""405        xmldoc = etree.fromstring(xml)406        obj = config.LibvirtConfigGuestDisk()407        obj.parse_dom(xmldoc)408        self.assertEqual(obj.source_type, 'file')409        self.assertEqual(obj.source_path, '/tmp/hello')410        self.assertEqual(obj.target_dev, '/dev/hda')411        self.assertEqual(obj.target_bus, 'ide')412    def test_config_file_serial(self):413        obj = config.LibvirtConfigGuestDisk()414        obj.source_type = "file"415        obj.source_path = "/tmp/hello"416        obj.target_dev = "/dev/hda"417        obj.target_bus = "ide"418        obj.serial = "7a97c4a3-6f59-41d4-bf47-191d7f97f8e9"419        xml = obj.to_xml()420        self.assertXmlEqual(xml, """421            <disk type="file" device="disk">422              <source file="/tmp/hello"/>423              <target bus="ide" dev="/dev/hda"/>424              <serial>7a97c4a3-6f59-41d4-bf47-191d7f97f8e9</serial>425            </disk>""")426    def test_config_file_serial_parse(self):427        xml = """<disk type="file" device="disk">428                   <source file="/tmp/hello"/>429                   <target bus="ide" dev="/dev/hda"/>430                   <serial>7a97c4a3-6f59-41d4-bf47-191d7f97f8e9</serial>431                 </disk>"""432        xmldoc = etree.fromstring(xml)433        obj = config.LibvirtConfigGuestDisk()434        obj.parse_dom(xmldoc)435        self.assertEqual(obj.source_type, 'file')436        self.assertEqual(obj.serial, '7a97c4a3-6f59-41d4-bf47-191d7f97f8e9')437    def test_config_file_discard(self):438        obj = config.LibvirtConfigGuestDisk()439        obj.driver_name = "qemu"440        obj.driver_format = "qcow2"441        obj.driver_cache = "none"442        obj.driver_discard = "unmap"443        obj.source_type = "file"444        obj.source_path = "/tmp/hello.qcow2"445        obj.target_dev = "/dev/hda"446        obj.target_bus = "ide"447        obj.serial = "7a97c4a3-6f59-41d4-bf47-191d7f97f8e9"448        xml = obj.to_xml()449        self.assertXmlEqual("""450            <disk type="file" device="disk">451              <driver name="qemu" type="qcow2" cache="none" discard="unmap"/>452              <source file="/tmp/hello.qcow2"/>453              <target bus="ide" dev="/dev/hda"/>454              <serial>7a97c4a3-6f59-41d4-bf47-191d7f97f8e9</serial>455            </disk>""", xml)456    def test_config_file_discard_parse(self):457        xml = """458            <disk type="file" device="disk">459              <driver name="qemu" type="qcow2" cache="none" discard="unmap"/>460              <source file="/tmp/hello.qcow2"/>461              <target bus="ide" dev="/dev/hda"/>462              <serial>7a97c4a3-6f59-41d4-bf47-191d7f97f8e9</serial>463            </disk>"""464        xmldoc = etree.fromstring(xml)465        obj = config.LibvirtConfigGuestDisk()466        obj.parse_dom(xmldoc)467        self.assertEqual('unmap', obj.driver_discard)468    def test_config_block(self):469        obj = config.LibvirtConfigGuestDisk()470        obj.source_type = "block"471        obj.source_path = "/tmp/hello"472        obj.source_device = "cdrom"473        obj.driver_name = "qemu"474        obj.target_dev = "/dev/hdc"475        obj.target_bus = "ide"476        xml = obj.to_xml()477        self.assertXmlEqual(xml, """478            <disk type="block" device="cdrom">479              <driver name="qemu"/>480              <source dev="/tmp/hello"/>481              <target bus="ide" dev="/dev/hdc"/>482            </disk>""")483    def test_config_block_parse(self):484        xml = """<disk type="block" device="cdrom">485                   <driver name="qemu"/>486                   <source dev="/tmp/hello"/>487                   <target bus="ide" dev="/dev/hdc"/>488                 </disk>"""489        xmldoc = etree.fromstring(xml)490        obj = config.LibvirtConfigGuestDisk()491        obj.parse_dom(xmldoc)492        self.assertEqual(obj.source_type, 'block')493        self.assertEqual(obj.source_path, '/tmp/hello')494        self.assertEqual(obj.target_dev, '/dev/hdc')495        self.assertEqual(obj.target_bus, 'ide')496    def test_config_network(self):497        obj = config.LibvirtConfigGuestDisk()498        obj.source_type = "network"499        obj.source_protocol = "iscsi"500        obj.source_name = "foo.bar.com"501        obj.driver_name = "qemu"502        obj.driver_format = "qcow2"503        obj.target_dev = "/dev/hda"504        obj.target_bus = "ide"505        xml = obj.to_xml()506        self.assertXmlEqual(xml, """507            <disk type="network" device="disk">508              <driver name="qemu" type="qcow2"/>509              <source name="foo.bar.com" protocol="iscsi"/>510              <target bus="ide" dev="/dev/hda"/>511            </disk>""")512    def test_config_network_parse(self):513        xml = """<disk type="network" device="disk">514                   <driver name="qemu" type="qcow2"/>515                   <source name="foo.bar.com" protocol="iscsi"/>516                   <target bus="ide" dev="/dev/hda"/>517                 </disk>"""518        xmldoc = etree.fromstring(xml)519        obj = config.LibvirtConfigGuestDisk()520        obj.parse_dom(xmldoc)521        self.assertEqual(obj.source_type, 'network')522        self.assertEqual(obj.source_protocol, 'iscsi')523        self.assertEqual(obj.source_name, 'foo.bar.com')524        self.assertEqual(obj.driver_name, 'qemu')525        self.assertEqual(obj.driver_format, 'qcow2')526        self.assertEqual(obj.target_dev, '/dev/hda')527        self.assertEqual(obj.target_bus, 'ide')528    def test_config_network_no_name(self):529        obj = config.LibvirtConfigGuestDisk()530        obj.source_type = 'network'531        obj.source_protocol = 'nbd'532        obj.source_hosts = ['foo.bar.com']533        obj.source_ports = [None]534        obj.driver_name = 'qemu'535        obj.driver_format = 'raw'536        obj.target_dev = '/dev/vda'537        obj.target_bus = 'virtio'538        xml = obj.to_xml()539        self.assertXmlEqual(xml, """540            <disk type="network" device="disk">541              <driver name="qemu" type="raw"/>542              <source protocol="nbd">543                <host name="foo.bar.com"/>544              </source>545              <target bus="virtio" dev="/dev/vda"/>546            </disk>""")547    def test_config_network_multihost(self):548        obj = config.LibvirtConfigGuestDisk()549        obj.source_type = 'network'550        obj.source_protocol = 'rbd'551        obj.source_name = 'pool/image'552        obj.source_hosts = ['foo.bar.com', '::1', '1.2.3.4']553        obj.source_ports = [None, '123', '456']554        obj.driver_name = 'qemu'555        obj.driver_format = 'raw'556        obj.target_dev = '/dev/vda'557        obj.target_bus = 'virtio'558        xml = obj.to_xml()559        self.assertXmlEqual(xml, """560            <disk type="network" device="disk">561              <driver name="qemu" type="raw"/>562              <source name="pool/image" protocol="rbd">563                <host name="foo.bar.com"/>564                <host name="::1" port="123"/>565                <host name="1.2.3.4" port="456"/>566              </source>567              <target bus="virtio" dev="/dev/vda"/>568            </disk>""")569    def test_config_network_auth(self):570        obj = config.LibvirtConfigGuestDisk()571        obj.source_type = "network"572        obj.source_protocol = "rbd"573        obj.source_name = "pool/image"574        obj.driver_name = "qemu"575        obj.driver_format = "raw"576        obj.target_dev = "/dev/vda"577        obj.target_bus = "virtio"578        obj.auth_username = "foo"579        obj.auth_secret_type = "ceph"580        obj.auth_secret_uuid = "b38a3f43-4be2-4046-897f-b67c2f5e0147"581        xml = obj.to_xml()582        self.assertXmlEqual(xml, """583            <disk type="network" device="disk">584              <driver name="qemu" type="raw"/>585              <source name="pool/image" protocol="rbd"/>586              <auth username="foo">587                <secret type="ceph"588                uuid="b38a3f43-4be2-4046-897f-b67c2f5e0147"/>589              </auth>590              <target bus="virtio" dev="/dev/vda"/>591            </disk>""")592    def test_config_iotune(self):593        obj = config.LibvirtConfigGuestDisk()594        obj.source_type = "file"595        obj.source_path = "/tmp/hello"596        obj.target_dev = "/dev/hda"597        obj.target_bus = "ide"598        obj.disk_read_bytes_sec = 1024000599        obj.disk_read_iops_sec = 1000600        obj.disk_total_bytes_sec = 2048000601        obj.disk_write_bytes_sec = 1024000602        obj.disk_write_iops_sec = 1000603        obj.disk_total_iops_sec = 2000604        xml = obj.to_xml()605        self.assertXmlEqual(xml, """606            <disk type="file" device="disk">607              <source file="/tmp/hello"/>608              <target bus="ide" dev="/dev/hda"/>609              <iotune>610                <read_bytes_sec>1024000</read_bytes_sec>611                <read_iops_sec>1000</read_iops_sec>612                <write_bytes_sec>1024000</write_bytes_sec>613                <write_iops_sec>1000</write_iops_sec>614                <total_bytes_sec>2048000</total_bytes_sec>615                <total_iops_sec>2000</total_iops_sec>616              </iotune>617            </disk>""")618    def test_config_blockio(self):619        obj = config.LibvirtConfigGuestDisk()620        obj.source_type = "file"621        obj.source_path = "/tmp/hello"622        obj.target_dev = "/dev/hda"623        obj.target_bus = "ide"624        obj.logical_block_size = "4096"625        obj.physical_block_size = "4096"626        xml = obj.to_xml()627        self.assertXmlEqual("""628            <disk type="file" device="disk">629              <source file="/tmp/hello"/>630              <target bus="ide" dev="/dev/hda"/>631              <blockio logical_block_size="4096" physical_block_size="4096"/>632            </disk>""", xml)633class LibvirtConfigGuestSnapshotDiskTest(LibvirtConfigBaseTest):634    def test_config_file(self):635        obj = config.LibvirtConfigGuestDisk()636        obj.source_type = "file"637        obj.source_path = "/tmp/hello"638        obj.target_dev = "/dev/hda"639        obj.target_bus = "ide"640        xml = obj.to_xml()641        self.assertXmlEqual(xml, """642            <disk type="file" device="disk">643              <source file="/tmp/hello"/>644              <target bus="ide" dev="/dev/hda"/>645            </disk>""")646    def test_config_file_parse(self):647        xml = """<disk type="file" device="disk">648                   <source file="/tmp/hello"/>649                   <target bus="ide" dev="/dev/hda"/>650                 </disk>"""651        xmldoc = etree.fromstring(xml)652        obj = config.LibvirtConfigGuestDisk()653        obj.parse_dom(xmldoc)654        self.assertEqual(obj.source_type, 'file')655        self.assertEqual(obj.source_path, '/tmp/hello')656        self.assertEqual(obj.target_dev, '/dev/hda')657        self.assertEqual(obj.target_bus, 'ide')658class LibvirtConfigGuestDiskBackingStoreTest(LibvirtConfigBaseTest):659    def test_config_file_parse(self):660        xml = """<backingStore type='file'>661                   <driver name='qemu' type='qcow2'/>662                   <source file='/var/lib/libvirt/images/mid.qcow2'/>663                   <backingStore type='file'>664                     <driver name='qemu' type='qcow2'/>665                     <source file='/var/lib/libvirt/images/base.qcow2'/>666                     <backingStore/>667                   </backingStore>668                 </backingStore>669              """670        xmldoc = etree.fromstring(xml)671        obj = config.LibvirtConfigGuestDiskBackingStore()672        obj.parse_dom(xmldoc)673        self.assertEqual(obj.driver_name, 'qemu')674        self.assertEqual(obj.driver_format, 'qcow2')675        self.assertEqual(obj.source_type, 'file')676        self.assertEqual(obj.source_file, '/var/lib/libvirt/images/mid.qcow2')677        self.assertEqual(obj.backing_store.driver_name, 'qemu')678        self.assertEqual(obj.backing_store.source_type, 'file')679        self.assertEqual(obj.backing_store.source_file,680                         '/var/lib/libvirt/images/base.qcow2')681        self.assertIsNone(obj.backing_store.backing_store)682    def test_config_network_parse(self):683        xml = """<backingStore type='network' index='1'>684                   <format type='qcow2'/>685                   <source protocol='gluster' name='volume1/img1'>686                     <host name='host1' port='24007'/>687                   </source>688                   <backingStore type='network' index='2'>689                     <format type='qcow2'/>690                     <source protocol='gluster' name='volume1/img2'>691                       <host name='host1' port='24007'/>692                     </source>693                     <backingStore/>694                   </backingStore>695                 </backingStore>696              """697        xmldoc = etree.fromstring(xml)698        obj = config.LibvirtConfigGuestDiskBackingStore()699        obj.parse_dom(xmldoc)700        self.assertEqual(obj.source_type, 'network')701        self.assertEqual(obj.source_protocol, 'gluster')702        self.assertEqual(obj.source_name, 'volume1/img1')703        self.assertEqual(obj.source_hosts[0], 'host1')704        self.assertEqual(obj.source_ports[0], '24007')705        self.assertEqual(obj.index, '1')706        self.assertEqual(obj.backing_store.source_name, 'volume1/img2')707        self.assertEqual(obj.backing_store.index, '2')708        self.assertEqual(obj.backing_store.source_hosts[0], 'host1')709        self.assertEqual(obj.backing_store.source_ports[0], '24007')710        self.assertIsNone(obj.backing_store.backing_store)711class LibvirtConfigGuestFilesysTest(LibvirtConfigBaseTest):712    def test_config_mount(self):713        obj = config.LibvirtConfigGuestFilesys()714        obj.source_type = "mount"715        obj.source_dir = "/tmp/hello"716        obj.target_dir = "/mnt"717        xml = obj.to_xml()718        self.assertXmlEqual(xml, """719            <filesystem type="mount">720              <source dir="/tmp/hello"/>721              <target dir="/mnt"/>722            </filesystem>""")723class LibvirtConfigGuestInputTest(LibvirtConfigBaseTest):724    def test_config_tablet(self):725        obj = config.LibvirtConfigGuestInput()726        xml = obj.to_xml()727        self.assertXmlEqual(xml, """728            <input type="tablet" bus="usb"/>""")729class LibvirtConfigGuestGraphicsTest(LibvirtConfigBaseTest):730    def test_config_graphics(self):731        obj = config.LibvirtConfigGuestGraphics()732        obj.type = "vnc"733        obj.autoport = True734        obj.keymap = "en_US"735        obj.listen = "127.0.0.1"736        xml = obj.to_xml()737        self.assertXmlEqual(xml, """738  <graphics type="vnc" autoport="yes" keymap="en_US" listen="127.0.0.1"/>739                            """)740class LibvirtConfigGuestHostdev(LibvirtConfigBaseTest):741    def test_config_pci_guest_host_dev(self):742        obj = config.LibvirtConfigGuestHostdev(mode='subsystem', type='pci')743        xml = obj.to_xml()744        expected = """745            <hostdev mode="subsystem" type="pci" managed="yes"/>746            """747        self.assertXmlEqual(xml, expected)748    def test_parse_GuestHostdev(self):749        xmldoc = """<hostdev mode="subsystem" type="pci" managed="yes"/>"""750        obj = config.LibvirtConfigGuestHostdev()751        obj.parse_str(xmldoc)752        self.assertEqual(obj.mode, 'subsystem')753        self.assertEqual(obj.type, 'pci')754        self.assertEqual(obj.managed, 'yes')755    def test_parse_GuestHostdev_non_pci(self):756        xmldoc = """<hostdev mode="subsystem" type="usb" managed="no"/>"""757        obj = config.LibvirtConfigGuestHostdev()758        obj.parse_str(xmldoc)759        self.assertEqual(obj.mode, 'subsystem')760        self.assertEqual(obj.type, 'usb')761        self.assertEqual(obj.managed, 'no')762class LibvirtConfigGuestHostdevPCI(LibvirtConfigBaseTest):763    expected = """764            <hostdev mode="subsystem" type="pci" managed="yes">765                <source>766                    <address bus="0x11" domain="0x1234" function="0x3"767                             slot="0x22" />768                </source>769            </hostdev>770            """771    def test_config_guest_hosdev_pci(self):772        hostdev = config.LibvirtConfigGuestHostdevPCI()773        hostdev.domain = "1234"774        hostdev.bus = "11"775        hostdev.slot = "22"776        hostdev.function = "3"777        xml = hostdev.to_xml()778        self.assertXmlEqual(self.expected, xml)779    def test_parse_guest_hosdev_pci(self):780        xmldoc = self.expected781        obj = config.LibvirtConfigGuestHostdevPCI()782        obj.parse_str(xmldoc)783        self.assertEqual(obj.mode, 'subsystem')784        self.assertEqual(obj.type, 'pci')785        self.assertEqual(obj.managed, 'yes')786        self.assertEqual(obj.domain, '0x1234')787        self.assertEqual(obj.bus, '0x11')788        self.assertEqual(obj.slot, '0x22')789        self.assertEqual(obj.function, '0x3')790    def test_parse_guest_hosdev_usb(self):791        xmldoc = """<hostdev mode='subsystem' type='usb'>792                      <source startupPolicy='optional'>793                          <vendor id='0x1234'/>794                          <product id='0xbeef'/>795                      </source>796                      <boot order='2'/>797                    </hostdev>"""798        obj = config.LibvirtConfigGuestHostdevPCI()799        obj.parse_str(xmldoc)800        self.assertEqual(obj.mode, 'subsystem')801        self.assertEqual(obj.type, 'usb')802class LibvirtConfigGuestSerialTest(LibvirtConfigBaseTest):803    def test_config_file(self):804        obj = config.LibvirtConfigGuestSerial()805        obj.type = "file"806        obj.source_path = "/tmp/vm.log"807        xml = obj.to_xml()808        self.assertXmlEqual(xml, """809            <serial type="file">810              <source path="/tmp/vm.log"/>811            </serial>""")812    def test_config_serial_port(self):813        obj = config.LibvirtConfigGuestSerial()814        obj.type = "tcp"815        obj.listen_port = 11111816        obj.listen_host = "0.0.0.0"817        xml = obj.to_xml()818        self.assertXmlEqual(xml, """819            <serial type="tcp">820              <source host="0.0.0.0" service="11111" mode="bind"/>821            </serial>""")822class LibvirtConfigGuestConsoleTest(LibvirtConfigBaseTest):823    def test_config_pty(self):824        obj = config.LibvirtConfigGuestConsole()825        obj.type = "pty"826        xml = obj.to_xml()827        self.assertXmlEqual(xml, """828            <console type="pty"/>""")829class LibvirtConfigGuestChannelTest(LibvirtConfigBaseTest):830    def test_config_spice_minimal(self):831        obj = config.LibvirtConfigGuestChannel()832        obj.type = "spicevmc"833        xml = obj.to_xml()834        self.assertXmlEqual(xml, """835            <channel type="spicevmc">836              <target type='virtio'/>837            </channel>""")838    def test_config_spice_full(self):839        obj = config.LibvirtConfigGuestChannel()840        obj.type = "spicevmc"841        obj.target_name = "com.redhat.spice.0"842        xml = obj.to_xml()843        self.assertXmlEqual(xml, """844            <channel type="spicevmc">845              <target type='virtio' name='com.redhat.spice.0'/>846            </channel>""")847    def test_config_qga_full(self):848        obj = config.LibvirtConfigGuestChannel()849        obj.type = "unix"850        obj.target_name = "org.qemu.guest_agent.0"851        obj.source_path = "/var/lib/libvirt/qemu/%s.%s.sock" % (852                            obj.target_name, "instance-name")853        xml = obj.to_xml()854        self.assertXmlEqual(xml, """855            <channel type="unix">856              <source path="%s" mode="bind"/>857              <target type="virtio" name="org.qemu.guest_agent.0"/>858            </channel>""" % obj.source_path)859class LibvirtConfigGuestInterfaceTest(LibvirtConfigBaseTest):860    def test_config_ethernet(self):861        obj = config.LibvirtConfigGuestInterface()862        obj.net_type = "ethernet"863        obj.mac_addr = "DE:AD:BE:EF:CA:FE"864        obj.model = "virtio"865        obj.target_dev = "vnet0"866        obj.driver_name = "vhost"867        obj.vif_inbound_average = 1024000868        obj.vif_inbound_peak = 10240000869        obj.vif_inbound_burst = 1024000870        obj.vif_outbound_average = 1024000871        obj.vif_outbound_peak = 10240000872        obj.vif_outbound_burst = 1024000873        xml = obj.to_xml()874        self.assertXmlEqual(xml, """875            <interface type="ethernet">876              <mac address="DE:AD:BE:EF:CA:FE"/>877              <model type="virtio"/>878              <driver name="vhost"/>879              <target dev="vnet0"/>880              <bandwidth>881                <inbound average="1024000" peak="10240000" burst="1024000"/>882                <outbound average="1024000" peak="10240000" burst="1024000"/>883              </bandwidth>884            </interface>""")885    def test_config_bridge(self):886        obj = config.LibvirtConfigGuestInterface()887        obj.net_type = "bridge"888        obj.source_dev = "br0"889        obj.mac_addr = "DE:AD:BE:EF:CA:FE"890        obj.model = "virtio"891        obj.target_dev = "tap12345678"892        obj.filtername = "clean-traffic"893        obj.filterparams.append({"key": "IP", "value": "192.168.122.1"})894        obj.vif_inbound_average = 1024000895        obj.vif_inbound_peak = 10240000896        obj.vif_inbound_burst = 1024000897        obj.vif_outbound_average = 1024000898        obj.vif_outbound_peak = 10240000899        obj.vif_outbound_burst = 1024000900        xml = obj.to_xml()901        self.assertXmlEqual(xml, """902            <interface type="bridge">903              <mac address="DE:AD:BE:EF:CA:FE"/>904              <model type="virtio"/>905              <source bridge="br0"/>906              <target dev="tap12345678"/>907              <filterref filter="clean-traffic">908                <parameter name="IP" value="192.168.122.1"/>909              </filterref>910              <bandwidth>911                <inbound average="1024000" peak="10240000" burst="1024000"/>912                <outbound average="1024000" peak="10240000" burst="1024000"/>913              </bandwidth>914            </interface>""")915    def test_config_bridge_ovs(self):916        obj = config.LibvirtConfigGuestInterface()917        obj.net_type = "bridge"918        obj.source_dev = "br0"919        obj.mac_addr = "DE:AD:BE:EF:CA:FE"920        obj.model = "virtio"921        obj.target_dev = "tap12345678"922        obj.vporttype = "openvswitch"923        obj.vportparams.append({"key": "instanceid", "value": "foobar"})924        xml = obj.to_xml()925        self.assertXmlEqual(xml, """926            <interface type="bridge">927              <mac address="DE:AD:BE:EF:CA:FE"/>928              <model type="virtio"/>929              <source bridge="br0"/>930              <target dev="tap12345678"/>931              <virtualport type="openvswitch">932                <parameters instanceid="foobar"/>933              </virtualport>934            </interface>""")935    def test_config_8021Qbh(self):936        obj = config.LibvirtConfigGuestInterface()937        obj.net_type = "direct"938        obj.mac_addr = "DE:AD:BE:EF:CA:FE"939        obj.model = "virtio"940        obj.target_dev = "tap12345678"941        obj.source_dev = "eth0"942        obj.vporttype = "802.1Qbh"943        xml = obj.to_xml()944        self.assertXmlEqual(xml, """945            <interface type="direct">946              <mac address="DE:AD:BE:EF:CA:FE"/>947              <model type="virtio"/>948              <source dev="eth0" mode="private"/>949              <target dev="tap12345678"/>950              <virtualport type="802.1Qbh"/>951            </interface>""")952    def test_config_direct(self):953        obj = config.LibvirtConfigGuestInterface()954        obj.net_type = "direct"955        obj.mac_addr = "DE:AD:BE:EF:CA:FE"956        obj.model = "virtio"957        obj.source_dev = "eth0"958        obj.source_mode = "passthrough"959        xml = obj.to_xml()960        self.assertXmlEqual(xml, """961            <interface type="direct">962              <mac address="DE:AD:BE:EF:CA:FE"/>963              <model type="virtio"/>964              <source dev="eth0" mode="passthrough"/>965            </interface>""")966    def test_config_8021Qbh_hostdev(self):967        obj = config.LibvirtConfigGuestInterface()968        obj.net_type = "hostdev"969        obj.mac_addr = "DE:AD:BE:EF:CA:FE"970        obj.source_dev = "0000:0a:00.1"971        obj.vporttype = "802.1Qbh"972        obj.add_vport_param("profileid", "MyPortProfile")973        xml = obj.to_xml()974        self.assertXmlEqual(xml, """975            <interface type="hostdev" managed="yes">976              <mac address="DE:AD:BE:EF:CA:FE"/>977              <source>978                <address type="pci" domain="0x0000"979                   bus="0x0a" slot="0x00" function="0x1"/>980              </source>981              <virtualport type="802.1Qbh">982                <parameters profileid="MyPortProfile"/>983              </virtualport>984            </interface>""")985    def test_config_hw_veb_hostdev(self):986        obj = config.LibvirtConfigGuestInterface()987        obj.net_type = "hostdev"988        obj.mac_addr = "DE:AD:BE:EF:CA:FE"989        obj.source_dev = "0000:0a:00.1"990        obj.vlan = "100"991        xml = obj.to_xml()992        self.assertXmlEqual(xml, """993            <interface type="hostdev" managed="yes">994              <mac address="DE:AD:BE:EF:CA:FE"/>995              <source>996                <address type="pci" domain="0x0000"997                   bus="0x0a" slot="0x00" function="0x1"/>998              </source>999              <vlan>1000               <tag id="100"/>1001              </vlan>1002            </interface>""")1003class LibvirtConfigGuestTest(LibvirtConfigBaseTest):1004    def test_config_lxc(self):1005        obj = config.LibvirtConfigGuest()1006        obj.virt_type = "lxc"1007        obj.memory = 100 * units.Mi1008        obj.vcpus = 21009        obj.cpuset = set([0, 1, 3, 4, 5])1010        obj.name = "demo"1011        obj.uuid = "b38a3f43-4be2-4046-897f-b67c2f5e0147"1012        obj.os_type = "exe"1013        obj.os_init_path = "/sbin/init"1014        fs = config.LibvirtConfigGuestFilesys()1015        fs.source_dir = "/root/lxc"1016        fs.target_dir = "/"1017        obj.add_device(fs)1018        xml = obj.to_xml()1019        self.assertXmlEqual(xml, """1020            <domain type="lxc">1021              <uuid>b38a3f43-4be2-4046-897f-b67c2f5e0147</uuid>1022              <name>demo</name>1023              <memory>104857600</memory>1024              <vcpu cpuset="0-1,3-5">2</vcpu>1025              <os>1026                <type>exe</type>1027                <init>/sbin/init</init>1028              </os>1029              <devices>1030                <filesystem type="mount">1031                  <source dir="/root/lxc"/>1032                  <target dir="/"/>1033                </filesystem>1034              </devices>1035            </domain>""")1036    def test_config_lxc_with_idmap(self):1037        obj = config.LibvirtConfigGuest()1038        obj.virt_type = "lxc"1039        obj.memory = 100 * units.Mi1040        obj.vcpus = 21041        obj.cpuset = set([0, 1, 3, 4, 5])1042        obj.name = "demo"1043        obj.uuid = "b38a3f43-4be2-4046-897f-b67c2f5e0147"1044        obj.os_type = "exe"1045        obj.os_init_path = "/sbin/init"1046        uidmap = config.LibvirtConfigGuestUIDMap()1047        uidmap.target = "10000"1048        uidmap.count = "1"1049        obj.idmaps.append(uidmap)1050        gidmap = config.LibvirtConfigGuestGIDMap()1051        gidmap.target = "10000"1052        gidmap.count = "1"1053        obj.idmaps.append(gidmap)1054        fs = config.LibvirtConfigGuestFilesys()1055        fs.source_dir = "/root/lxc"1056        fs.target_dir = "/"1057        obj.add_device(fs)1058        xml = obj.to_xml()1059        self.assertXmlEqual("""1060            <domain type="lxc">1061              <uuid>b38a3f43-4be2-4046-897f-b67c2f5e0147</uuid>1062              <name>demo</name>1063              <memory>104857600</memory>1064              <vcpu cpuset="0-1,3-5">2</vcpu>1065              <os>1066                <type>exe</type>1067                <init>/sbin/init</init>1068              </os>1069              <devices>1070                <filesystem type="mount">1071                  <source dir="/root/lxc"/>1072                  <target dir="/"/>1073                </filesystem>1074              </devices>1075              <idmap>1076                <uid start="0" target="10000" count="1"/>1077                <gid start="0" target="10000" count="1"/>1078              </idmap>1079            </domain>""", xml)1080    def test_config_xen_pv(self):1081        obj = config.LibvirtConfigGuest()1082        obj.virt_type = "xen"1083        obj.memory = 100 * units.Mi1084        obj.vcpus = 21085        obj.cpuset = set([0, 1, 3, 4, 5])1086        obj.name = "demo"1087        obj.uuid = "b38a3f43-4be2-4046-897f-b67c2f5e0147"1088        obj.os_type = "linux"1089        obj.os_kernel = "/tmp/vmlinuz"1090        obj.os_initrd = "/tmp/ramdisk"1091        obj.os_cmdline = "console=xvc0"1092        disk = config.LibvirtConfigGuestDisk()1093        disk.source_type = "file"1094        disk.source_path = "/tmp/img"1095        disk.target_dev = "/dev/xvda"1096        disk.target_bus = "xen"1097        obj.add_device(disk)1098        xml = obj.to_xml()1099        self.assertXmlEqual(xml, """1100            <domain type="xen">1101              <uuid>b38a3f43-4be2-4046-897f-b67c2f5e0147</uuid>1102              <name>demo</name>1103              <memory>104857600</memory>1104              <vcpu cpuset="0-1,3-5">2</vcpu>1105              <os>1106                <type>linux</type>1107                <kernel>/tmp/vmlinuz</kernel>1108                <initrd>/tmp/ramdisk</initrd>1109                <cmdline>console=xvc0</cmdline>1110              </os>1111              <devices>1112                <disk type="file" device="disk">1113                  <source file="/tmp/img"/>1114                  <target bus="xen" dev="/dev/xvda"/>1115                </disk>1116              </devices>1117            </domain>""")1118    def test_config_xen_hvm(self):1119        obj = config.LibvirtConfigGuest()1120        obj.virt_type = "xen"1121        obj.memory = 100 * units.Mi1122        obj.vcpus = 21123        obj.cpuset = set([0, 1, 3, 4, 5])1124        obj.name = "demo"1125        obj.uuid = "b38a3f43-4be2-4046-897f-b67c2f5e0147"1126        obj.os_type = "hvm"1127        obj.os_loader = '/usr/lib/xen/boot/hvmloader'1128        obj.os_root = "root=xvda"1129        obj.os_cmdline = "console=xvc0"1130        obj.pae = True1131        obj.acpi = True1132        obj.apic = True1133        disk = config.LibvirtConfigGuestDisk()1134        disk.source_type = "file"1135        disk.source_path = "/tmp/img"1136        disk.target_dev = "/dev/xvda"1137        disk.target_bus = "xen"1138        obj.add_device(disk)1139        xml = obj.to_xml()1140        self.assertXmlEqual(xml, """1141            <domain type="xen">1142              <uuid>b38a3f43-4be2-4046-897f-b67c2f5e0147</uuid>1143              <name>demo</name>1144              <memory>104857600</memory>1145              <vcpu cpuset="0-1,3-5">2</vcpu>1146              <os>1147                <type>hvm</type>1148                <loader>/usr/lib/xen/boot/hvmloader</loader>1149                <cmdline>console=xvc0</cmdline>1150                <root>root=xvda</root>1151              </os>1152              <features>1153                <acpi/>1154                <apic/>1155                <pae/>1156              </features>1157              <devices>1158                <disk type="file" device="disk">1159                  <source file="/tmp/img"/>1160                  <target bus="xen" dev="/dev/xvda"/>1161                </disk>1162              </devices>1163            </domain>""")1164    def test_config_kvm(self):1165        obj = config.LibvirtConfigGuest()1166        obj.virt_type = "kvm"1167        obj.memory = 100 * units.Mi1168        obj.vcpus = 21169        obj.cpuset = set([0, 1, 3, 4, 5])1170        obj.cputune = config.LibvirtConfigGuestCPUTune()1171        obj.cputune.shares = 1001172        obj.cputune.quota = 500001173        obj.cputune.period = 250001174        obj.membacking = config.LibvirtConfigGuestMemoryBacking()1175        obj.membacking.hugepages = True1176        obj.memtune = config.LibvirtConfigGuestMemoryTune()1177        obj.memtune.hard_limit = 4961178        obj.memtune.soft_limit = 6721179        obj.memtune.swap_hard_limit = 16381180        obj.memtune.min_guarantee = 29701181        obj.name = "demo"1182        obj.uuid = "b38a3f43-4be2-4046-897f-b67c2f5e0147"1183        obj.os_type = "linux"1184        obj.os_boot_dev = ["hd", "cdrom", "fd"]1185        obj.os_smbios = config.LibvirtConfigGuestSMBIOS()1186        obj.pae = True1187        obj.acpi = True1188        obj.apic = True1189        obj.sysinfo = config.LibvirtConfigGuestSysinfo()1190        obj.sysinfo.bios_vendor = "Acme"1191        obj.sysinfo.system_version = "1.0.0"1192        disk = config.LibvirtConfigGuestDisk()1193        disk.source_type = "file"1194        disk.source_path = "/tmp/img"1195        disk.target_dev = "/dev/vda"1196        disk.target_bus = "virtio"1197        obj.add_device(disk)1198        xml = obj.to_xml()1199        self.assertXmlEqual(xml, """1200            <domain type="kvm">1201              <uuid>b38a3f43-4be2-4046-897f-b67c2f5e0147</uuid>1202              <name>demo</name>1203              <memory>104857600</memory>1204              <memoryBacking>1205                <hugepages/>1206              </memoryBacking>1207              <memtune>1208                <hard_limit units="K">496</hard_limit>1209                <soft_limit units="K">672</soft_limit>1210                <swap_hard_limit units="K">1638</swap_hard_limit>1211                <min_guarantee units="K">2970</min_guarantee>1212              </memtune>1213              <vcpu cpuset="0-1,3-5">2</vcpu>1214              <sysinfo type='smbios'>1215                 <bios>1216                   <entry name="vendor">Acme</entry>1217                 </bios>1218                 <system>1219                   <entry name="version">1.0.0</entry>1220                 </system>1221              </sysinfo>1222              <os>1223                <type>linux</type>1224                <boot dev="hd"/>1225                <boot dev="cdrom"/>1226                <boot dev="fd"/>1227                <smbios mode="sysinfo"/>1228              </os>1229              <features>1230                <acpi/>1231                <apic/>1232                <pae/>1233              </features>1234              <cputune>1235                <shares>100</shares>1236                <quota>50000</quota>1237                <period>25000</period>1238              </cputune>1239              <devices>1240                <disk type="file" device="disk">1241                  <source file="/tmp/img"/>1242                  <target bus="virtio" dev="/dev/vda"/>1243                </disk>1244              </devices>1245            </domain>""")1246    def test_config_machine_type(self):1247        obj = config.LibvirtConfigGuest()1248        obj.virt_type = "kvm"1249        obj.memory = 100 * units.Mi1250        obj.vcpus = 21251        obj.name = "demo"1252        obj.uuid = "b38a3f43-4be2-4046-897f-b67c2f5e0147"1253        obj.os_type = "hvm"1254        obj.os_mach_type = "fake_machine_type"1255        xml = obj.to_xml()1256        self.assertXmlEqual(xml, """1257            <domain type="kvm">1258              <uuid>b38a3f43-4be2-4046-897f-b67c2f5e0147</uuid>1259              <name>demo</name>1260              <memory>104857600</memory>1261              <vcpu>2</vcpu>1262              <os>1263                <type machine="fake_machine_type">hvm</type>1264              </os>1265            </domain>""")1266    def test_ConfigGuest_parse_devices(self):1267        xmldoc = """ <domain type="kvm">1268                      <devices>1269                        <hostdev mode="subsystem" type="pci" managed="no">1270                        </hostdev>1271                      </devices>1272                     </domain>1273                 """1274        obj = config.LibvirtConfigGuest()1275        obj.parse_str(xmldoc)1276        self.assertEqual(len(obj.devices), 1)1277        self.assertIsInstance(obj.devices[0],1278                              config.LibvirtConfigGuestHostdevPCI)1279        self.assertEqual(obj.devices[0].mode, 'subsystem')1280        self.assertEqual(obj.devices[0].managed, 'no')1281    def test_ConfigGuest_parse_devices_wrong_type(self):1282        xmldoc = """ <domain type="kvm">1283                      <devices>1284                        <hostdev mode="subsystem" type="xxxx" managed="no">1285                        </hostdev>1286                      </devices>1287                     </domain>1288                 """1289        obj = config.LibvirtConfigGuest()1290        obj.parse_str(xmldoc)1291        self.assertEqual(len(obj.devices), 0)1292    def test_ConfigGuest_parese_cpu(self):1293        xmldoc = """ <domain>1294                       <cpu mode='custom' match='exact'>1295                         <model>kvm64</model>1296                       </cpu>1297                     </domain>1298                """1299        obj = config.LibvirtConfigGuest()1300        obj.parse_str(xmldoc)1301        self.assertEqual(obj.cpu.mode, 'custom')1302        self.assertEqual(obj.cpu.match, 'exact')1303        self.assertEqual(obj.cpu.model, 'kvm64')1304class LibvirtConfigGuestSnapshotTest(LibvirtConfigBaseTest):1305    def test_config_snapshot(self):1306        obj = config.LibvirtConfigGuestSnapshot()1307        obj.name = "Demo"1308        xml = obj.to_xml()1309        self.assertXmlEqual(xml, """1310            <domainsnapshot>1311              <name>Demo</name>1312              <disks/>1313            </domainsnapshot>""")1314    def test_config_snapshot_with_disks(self):1315        obj = config.LibvirtConfigGuestSnapshot()1316        obj.name = "Demo"1317        disk = config.LibvirtConfigGuestSnapshotDisk()1318        disk.name = 'vda'1319        disk.source_path = 'source-path'1320        disk.source_type = 'file'1321        disk.snapshot = 'external'1322        disk.driver_name = 'qcow2'1323        obj.add_disk(disk)1324        disk2 = config.LibvirtConfigGuestSnapshotDisk()1325        disk2.name = 'vdb'1326        disk2.snapshot = 'no'1327        obj.add_disk(disk2)1328        xml = obj.to_xml()1329        self.assertXmlEqual(xml, """1330            <domainsnapshot>1331              <name>Demo</name>1332              <disks>1333               <disk name='vda' snapshot='external' type='file'>1334                <source file='source-path'/>1335               </disk>1336               <disk name='vdb' snapshot='no'/>1337              </disks>1338            </domainsnapshot>""")1339    def test_config_snapshot_with_network_disks(self):1340        obj = config.LibvirtConfigGuestSnapshot()1341        obj.name = "Demo"1342        disk = config.LibvirtConfigGuestSnapshotDisk()1343        disk.name = 'vda'1344        disk.source_name = 'source-file'1345        disk.source_type = 'network'1346        disk.source_hosts = ['host1']1347        disk.source_ports = ['12345']1348        disk.source_protocol = 'glusterfs'1349        disk.snapshot = 'external'1350        disk.driver_name = 'qcow2'1351        obj.add_disk(disk)1352        disk2 = config.LibvirtConfigGuestSnapshotDisk()1353        disk2.name = 'vdb'1354        disk2.snapshot = 'no'1355        obj.add_disk(disk2)1356        xml = obj.to_xml()1357        self.assertXmlEqual(xml, """1358            <domainsnapshot>1359              <name>Demo</name>1360              <disks>1361               <disk name='vda' snapshot='external' type='network'>1362                <source protocol='glusterfs' name='source-file'>1363                 <host name='host1' port='12345'/>1364                </source>1365               </disk>1366               <disk name='vdb' snapshot='no'/>1367              </disks>1368            </domainsnapshot>""")1369class LibvirtConfigNodeDeviceTest(LibvirtConfigBaseTest):1370    def test_config_virt_usb_device(self):1371        xmlin = """1372        <device>1373          <name>usb_0000_09_00_0</name>1374          <parent>pci_0000_00_1c_0</parent>1375          <driver>1376          <name>vxge</name>1377          </driver>1378          <capability type="usb">1379            <domain>0</domain>1380             <capability type="fake_usb">1381             <address fake_usb="fake"/>1382            </capability>1383          </capability>1384        </device>"""1385        obj = config.LibvirtConfigNodeDevice()1386        obj.parse_str(xmlin)1387        self.assertIsNone(obj.pci_capability)1388    def test_config_virt_device(self):1389        xmlin = """1390        <device>1391          <name>pci_0000_09_00_0</name>1392          <parent>pci_0000_00_1c_0</parent>1393          <driver>1394          <name>vxge</name>1395          </driver>1396          <capability type="pci">1397            <domain>0</domain>1398            <bus>9</bus>1399            <slot>0</slot>1400            <function>0</function>1401        <product id="0x5833">X3100 Series 10 Gigabit Ethernet PCIe</product>1402            <vendor id="0x17d5">Neterion Inc.</vendor>1403            <capability type="virt_functions">1404             <address domain="0x0000" bus="0x0a" slot="0x00" function="0x1"/>1405             <address domain="0x0000" bus="0x0a" slot="0x00" function="0x2"/>1406             <address domain="0x0000" bus="0x0a" slot="0x00" function="0x3"/>1407            </capability>1408          </capability>1409        </device>"""1410        obj = config.LibvirtConfigNodeDevice()1411        obj.parse_str(xmlin)1412        self.assertIsInstance(obj.pci_capability,1413                              config.LibvirtConfigNodeDevicePciCap)1414        self.assertIsInstance(obj.pci_capability.fun_capability[0],1415                              config.LibvirtConfigNodeDevicePciSubFunctionCap)1416        self.assertEqual(obj.pci_capability.fun_capability[0].type,1417                          "virt_functions")1418        self.assertEqual(len(obj.pci_capability.fun_capability[0].1419                             device_addrs),1420                          3)1421        self.assertEqual(obj.pci_capability.bus, 9)1422    def test_config_phy_device(self):1423        xmlin = """1424        <device>1425          <name>pci_0000_33_00_0</name>1426          <parent>pci_0000_22_1c_0</parent>1427          <driver>1428          <name>vxx</name>1429          </driver>1430          <capability type="pci">1431            <domain>0</domain>1432            <bus>9</bus>1433            <slot>0</slot>1434            <function>0</function>1435           <product id="0x5833">X3100 Series 10 Gigabit Ethernet PCIe</product>1436            <vendor id="0x17d5">Neterion Inc.</vendor>1437            <capability type="phys_function">1438            <address domain='0x0000' bus='0x09' slot='0x00' function='0x0'/>1439            </capability>1440          </capability>1441        </device>"""1442        obj = config.LibvirtConfigNodeDevice()1443        obj.parse_str(xmlin)1444        self.assertIsInstance(obj.pci_capability,1445                              config.LibvirtConfigNodeDevicePciCap)1446        self.assertIsInstance(obj.pci_capability.fun_capability[0],1447                              config.LibvirtConfigNodeDevicePciSubFunctionCap)1448        self.assertEqual(obj.pci_capability.fun_capability[0].type,1449                          "phys_function")1450        self.assertEqual(len(obj.pci_capability.fun_capability[0].1451                             device_addrs),1452                         1)1453    def test_config_non_device(self):1454        xmlin = """1455        <device>1456          <name>pci_0000_33_00_0</name>1457          <parent>pci_0000_22_1c_0</parent>1458          <driver>1459          <name>vxx</name>1460          </driver>1461          <capability type="pci">1462            <domain>0</domain>1463            <bus>9</bus>1464            <slot>0</slot>1465            <function>0</function>1466          <product id="0x5833">X3100 Series 10 Gigabit Ethernet PCIe</product>1467             <vendor id="0x17d5">Neterion Inc.</vendor>1468             <capability type="virt_functions"/>1469          </capability>1470        </device>"""1471        obj = config.LibvirtConfigNodeDevice()1472        obj.parse_str(xmlin)1473        self.assertIsInstance(obj.pci_capability,1474                              config.LibvirtConfigNodeDevicePciCap)1475        self.assertIsInstance(obj.pci_capability.fun_capability[0],1476                              config.LibvirtConfigNodeDevicePciSubFunctionCap)1477        self.assertEqual(obj.pci_capability.fun_capability[0].type,1478                          "virt_functions")1479    def test_config_fail_device(self):1480        xmlin = """1481        <device>1482          <name>pci_0000_33_00_0</name>1483          <parent>pci_0000_22_1c_0</parent>1484          <driver>1485          <name>vxx</name>1486          </driver>1487          <capability type="pci">1488            <domain>0</domain>1489            <bus>9</bus>1490            <slot>0</slot>1491            <function>0</function>1492         <product id="0x5833">X3100 Series 10 Gigabit Ethernet PCIe</product>1493            <vendor id="0x17d5">Neterion Inc.</vendor>1494            <capability type="virt_functions">1495            </capability>1496          </capability>1497        </device>"""1498        obj = config.LibvirtConfigNodeDevice()1499        obj.parse_str(xmlin)1500        self.assertIsInstance(obj.pci_capability,1501                              config.LibvirtConfigNodeDevicePciCap)1502        self.assertIsInstance(obj.pci_capability.fun_capability[0],1503                              config.LibvirtConfigNodeDevicePciSubFunctionCap)1504        self.assertEqual(obj.pci_capability.fun_capability[0].type,1505                          "virt_functions")1506    def test_config_2cap_device(self):1507        xmlin = """1508        <device>1509          <name>pci_0000_04_10_7</name>1510          <parent>pci_0000_00_01_1</parent>1511          <driver>1512            <name>igbvf</name>1513          </driver>1514          <capability type='pci'>1515            <domain>0</domain>1516            <bus>4</bus>1517            <slot>16</slot>1518            <function>7</function>1519            <product id='0x1520'>I350 Ethernet Controller Virtual</product>1520            <vendor id='0x8086'>Intel Corporation</vendor>1521            <capability type='phys_function'>1522              <address domain='0x0000' bus='0x04' slot='0x00' function='0x3'/>1523            </capability>1524            <capability type='virt_functions'>1525              <address domain='0x0000' bus='0x04' slot='0x00' function='0x3'/>1526            </capability>1527          </capability>1528        </device>"""1529        obj = config.LibvirtConfigNodeDevice()1530        obj.parse_str(xmlin)1531        self.assertIsInstance(obj.pci_capability,1532                              config.LibvirtConfigNodeDevicePciCap)1533        self.assertIsInstance(obj.pci_capability.fun_capability[0],1534                              config.LibvirtConfigNodeDevicePciSubFunctionCap)1535        self.assertEqual(obj.pci_capability.fun_capability[0].type,1536                          "phys_function")1537        self.assertEqual(obj.pci_capability.fun_capability[1].type,1538                          "virt_functions")1539class LibvirtConfigNodeDevicePciCapTest(LibvirtConfigBaseTest):1540    def test_config_device_pci_cap(self):1541        xmlin = """1542            <capability type="pci">1543              <domain>0</domain>1544              <bus>10</bus>1545              <slot>1</slot>1546              <function>5</function>1547              <product id="0x8086-3">Intel 10 Gigabit Ethernet</product>1548              <vendor id="0x8086">Intel Inc.</vendor>1549              <capability type="virt_functions">1550               <address domain="0000" bus="0x0a" slot="0x1" function="0x1"/>1551               <address domain="0001" bus="0x0a" slot="0x02" function="0x03"/>1552              </capability>1553            </capability>"""1554        obj = config.LibvirtConfigNodeDevicePciCap()1555        obj.parse_str(xmlin)1556        self.assertEqual(obj.domain, 0)1557        self.assertEqual(obj.bus, 10)1558        self.assertEqual(obj.slot, 1)1559        self.assertEqual(obj.function, 5)1560        self.assertEqual(obj.product, "Intel 10 Gigabit Ethernet")1561        self.assertEqual(obj.product_id, '0x8086-3')1562        self.assertEqual(obj.vendor, "Intel Inc.")1563        self.assertEqual(obj.vendor_id, "0x8086")1564        self.assertIsInstance(obj.fun_capability[0],1565                              config.LibvirtConfigNodeDevicePciSubFunctionCap)1566        self.assertEqual(obj.fun_capability[0].type, 'virt_functions')1567        self.assertEqual(obj.fun_capability[0].device_addrs,1568                         [("0000", "0x0a", "0x1", "0x1"),1569                          ("0001", "0x0a", "0x02", "0x03"), ])1570    def test_config_device_pci_2cap(self):1571        xmlin = """1572            <capability type="pci">1573              <domain>0</domain>1574              <bus>10</bus>1575              <slot>1</slot>1576              <function>5</function>1577              <product id="0x8086-3">Intel 10 Gigabit Ethernet</product>1578              <vendor id="0x8086">Intel Inc.</vendor>1579              <capability type="virt_functions">1580               <address domain="0000" bus="0x0a" slot="0x1" function="0x1"/>1581               <address domain="0001" bus="0x0a" slot="0x02" function="0x03"/>1582              </capability>1583              <capability type="phys_function">1584               <address domain="0000" bus="0x0a" slot="0x1" function="0x1"/>1585              </capability>1586            </capability>"""1587        obj = config.LibvirtConfigNodeDevicePciCap()1588        obj.parse_str(xmlin)1589        self.assertEqual(obj.domain, 0)1590        self.assertEqual(obj.bus, 10)1591        self.assertEqual(obj.slot, 1)1592        self.assertEqual(obj.function, 5)1593        self.assertEqual(obj.product, "Intel 10 Gigabit Ethernet")1594        self.assertEqual(obj.product_id, '0x8086-3')1595        self.assertEqual(obj.vendor, "Intel Inc.")1596        self.assertEqual(obj.vendor_id, "0x8086")1597        self.assertIsInstance(obj.fun_capability[0],1598                              config.LibvirtConfigNodeDevicePciSubFunctionCap)1599        self.assertEqual(obj.fun_capability[0].type, 'virt_functions')1600        self.assertEqual(obj.fun_capability[0].device_addrs,1601                         [("0000", '0x0a', '0x1', "0x1"),1602                          ("0001", "0x0a", "0x02", "0x03"), ])1603        self.assertEqual(obj.fun_capability[1].type, 'phys_function')1604        self.assertEqual(obj.fun_capability[1].device_addrs,1605                         [("0000", '0x0a', '0x1', "0x1"), ])1606        def test_config_read_only_disk(self):1607            obj = config.LibvirtConfigGuestDisk()1608            obj.source_type = "disk"1609            obj.source_device = "disk"1610            obj.driver_name = "kvm"1611            obj.target_dev = "/dev/hdc"1612            obj.target_bus = "virtio"1613            obj.readonly = True1614            xml = obj.to_xml()1615            self.assertXmlEqual(xml, """1616                <disk type="disk" device="disk">1617                    <driver name="kvm"/>1618                    <target bus="virtio" dev="/dev/hdc"/>1619                    <readonly/>1620                </disk>""")1621            obj.readonly = False1622            xml = obj.to_xml()1623            self.assertXmlEqual(xml, """1624                <disk type="disk" device="disk">1625                    <driver name="kvm"/>1626                    <target bus="virtio" dev="/dev/hdc"/>1627                </disk>""")1628class LibvirtConfigNodeDevicePciSubFunctionCap(LibvirtConfigBaseTest):1629    def test_config_device_pci_subfunction(self):1630        xmlin = """1631        <capability type="virt_functions">1632            <address domain="0000" bus="0x0a" slot="0x1" function="0x1"/>1633            <address domain="0001" bus="0x0a" slot="0x02" function="0x03"/>1634        </capability>"""1635        fun_capability = config.LibvirtConfigNodeDevicePciSubFunctionCap()1636        fun_capability.parse_str(xmlin)1637        self.assertEqual('virt_functions', fun_capability.type)1638        self.assertEqual([("0000", "0x0a", "0x1", "0x1"),1639                          ("0001", "0x0a", "0x02", "0x03"), ],1640                         fun_capability.device_addrs)1641class LibvirtConfigGuestVideoTest(LibvirtConfigBaseTest):1642    def test_config_video_driver(self):1643        obj = config.LibvirtConfigGuestVideo()1644        obj.type = 'qxl'1645        xml = obj.to_xml()1646        self.assertXmlEqual(xml, """1647                <video>1648                    <model type='qxl'/>1649                </video>""")1650    def test_config_video_driver_vram_heads(self):1651        obj = config.LibvirtConfigGuestVideo()1652        obj.type = 'qxl'1653        obj.vram = '9216'1654        obj.heads = '1'1655        xml = obj.to_xml()1656        self.assertXmlEqual(xml, """1657                <video>1658                    <model type='qxl' vram='9216' heads='1'/>1659                </video>""")1660class LibvirtConfigGuestSeclabel(LibvirtConfigBaseTest):1661    def test_config_seclabel_config(self):1662        obj = config.LibvirtConfigSeclabel()1663        xml = obj.to_xml()1664        self.assertXmlEqual(xml, """1665              <seclabel type='dynamic'/>""")1666    def test_config_seclabel_baselabel(self):1667        obj = config.LibvirtConfigSeclabel()1668        obj.type = 'dynamic'1669        obj.baselabel = 'system_u:system_r:my_svirt_t:s0'1670        xml = obj.to_xml()1671        self.assertXmlEqual(xml, """1672              <seclabel type='dynamic'>1673                <baselabel>system_u:system_r:my_svirt_t:s0</baselabel>1674              </seclabel>""")1675class LibvirtConfigGuestRngTest(LibvirtConfigBaseTest):1676    def test_config_rng_driver(self):1677        obj = config.LibvirtConfigGuestRng()1678        xml = obj.to_xml()1679        self.assertXmlEqual(xml, """1680<rng model='virtio'>1681    <backend model='random'/>1682</rng>""")1683    def test_config_rng_driver_with_rate(self):1684        obj = config.LibvirtConfigGuestRng()1685        obj.backend = '/dev/random'1686        obj.rate_period = '12'1687        obj.rate_bytes = '34'1688        xml = obj.to_xml()1689        self.assertXmlEqual(xml, """1690<rng model='virtio'>1691    <rate period='12' bytes='34'/>1692    <backend model='random'>/dev/random</backend>1693</rng>""")1694class LibvirtConfigGuestControllerTest(LibvirtConfigBaseTest):1695    def test_config_guest_contoller(self):1696        obj = config.LibvirtConfigGuestController()1697        obj.type = 'scsi'1698        obj.index = 01699        obj.model = 'virtio-scsi'1700        xml = obj.to_xml()1701        self.assertXmlEqual(xml, """1702                <controller type='scsi' index='0' model='virtio-scsi'/>""")1703class LibvirtConfigGuestWatchdogTest(LibvirtConfigBaseTest):1704    def test_config_watchdog(self):1705        obj = config.LibvirtConfigGuestWatchdog()1706        obj.action = 'none'1707        xml = obj.to_xml()1708        self.assertXmlEqual(xml, "<watchdog model='i6300esb' action='none'/>")1709    def test_config_watchdog_default_action(self):1710        obj = config.LibvirtConfigGuestWatchdog()1711        xml = obj.to_xml()1712        self.assertXmlEqual(xml, "<watchdog model='i6300esb' action='reset'/>")1713class LibvirtConfigGuestCPUTuneTest(LibvirtConfigBaseTest):1714    def test_config_cputune_timeslice(self):1715        cputune = config.LibvirtConfigGuestCPUTune()1716        cputune.shares = 1001717        cputune.quota = 500001718        cputune.period = 250001719        xml = cputune.to_xml()1720        self.assertXmlEqual(xml, """1721          <cputune>1722            <shares>100</shares>1723            <quota>50000</quota>1724            <period>25000</period>1725          </cputune>""")1726    def test_config_cputune_vcpus(self):1727        cputune = config.LibvirtConfigGuestCPUTune()1728        vcpu0 = config.LibvirtConfigGuestCPUTuneVCPUPin()1729        vcpu0.id = 01730        vcpu0.cpuset = set([0, 1])1731        vcpu1 = config.LibvirtConfigGuestCPUTuneVCPUPin()1732        vcpu1.id = 11733        vcpu1.cpuset = set([2, 3])1734        vcpu2 = config.LibvirtConfigGuestCPUTuneVCPUPin()1735        vcpu2.id = 21736        vcpu2.cpuset = set([4, 5])1737        vcpu3 = config.LibvirtConfigGuestCPUTuneVCPUPin()1738        vcpu3.id = 31739        vcpu3.cpuset = set([6, 7])1740        cputune.vcpupin.extend([vcpu0, vcpu1, vcpu2, vcpu3])1741        xml = cputune.to_xml()1742        self.assertXmlEqual(xml, """1743          <cputune>1744            <vcpupin vcpu="0" cpuset="0-1"/>1745            <vcpupin vcpu="1" cpuset="2-3"/>1746            <vcpupin vcpu="2" cpuset="4-5"/>1747            <vcpupin vcpu="3" cpuset="6-7"/>1748          </cputune>""")1749class LibvirtConfigGuestMemoryBackingTest(LibvirtConfigBaseTest):1750    def test_config_memory_backing_none(self):1751        obj = config.LibvirtConfigGuestMemoryBacking()1752        xml = obj.to_xml()1753        self.assertXmlEqual(xml, "<memoryBacking/>")1754    def test_config_memory_backing_all(self):1755        obj = config.LibvirtConfigGuestMemoryBacking()1756        obj.locked = True1757        obj.sharedpages = False1758        obj.hugepages = True1759        xml = obj.to_xml()1760        self.assertXmlEqual(xml, """1761          <memoryBacking>1762            <hugepages/>1763            <nosharedpages/>1764            <locked/>1765          </memoryBacking>""")1766class LibvirtConfigGuestMemoryTuneTest(LibvirtConfigBaseTest):1767    def test_config_memory_backing_none(self):1768        obj = config.LibvirtConfigGuestMemoryTune()1769        xml = obj.to_xml()1770        self.assertXmlEqual(xml, "<memtune/>")1771    def test_config_memory_backing_all(self):1772        obj = config.LibvirtConfigGuestMemoryTune()1773        obj.soft_limit = 61774        obj.hard_limit = 281775        obj.swap_hard_limit = 1401776        obj.min_guarantee = 2701777        xml = obj.to_xml()1778        self.assertXmlEqual(xml, """1779          <memtune>1780            <hard_limit units="K">28</hard_limit>1781            <soft_limit units="K">6</soft_limit>1782            <swap_hard_limit units="K">140</swap_hard_limit>1783            <min_guarantee units="K">270</min_guarantee>1784          </memtune>""")1785class LibvirtConfigGuestMetadataNovaTest(LibvirtConfigBaseTest):1786    def test_config_metadata(self):1787        meta = config.LibvirtConfigGuestMetaNovaInstance()1788        meta.package = "2014.2.3"1789        meta.name = "moonbuggy"1790        meta.creationTime = 12345678901791        meta.roottype = "image"1792        meta.rootid = "fe55c69a-8b2e-4bbc-811a-9ad2023a0426"1793        owner = config.LibvirtConfigGuestMetaNovaOwner()1794        owner.userid = "3472c2a6-de91-4fb5-b618-42bc781ef670"1795        owner.username = "buzz"1796        owner.projectid = "f241e906-010e-4917-ae81-53f4fb8aa021"1797        owner.projectname = "moonshot"1798        meta.owner = owner1799        flavor = config.LibvirtConfigGuestMetaNovaFlavor()1800        flavor.name = "m1.lowgravity"1801        flavor.vcpus = 81802        flavor.memory = 20481803        flavor.swap = 101804        flavor.disk = 501805        flavor.ephemeral = 101806        meta.flavor = flavor1807        xml = meta.to_xml()1808        self.assertXmlEqual(xml, """1809    <nova:instance xmlns:nova='http://openstack.org/xmlns/libvirt/nova/1.0'>1810      <nova:package version="2014.2.3"/>1811      <nova:name>moonbuggy</nova:name>1812      <nova:creationTime>2009-02-13 23:31:30</nova:creationTime>1813      <nova:flavor name="m1.lowgravity">1814        <nova:memory>2048</nova:memory>1815        <nova:disk>50</nova:disk>1816        <nova:swap>10</nova:swap>1817        <nova:ephemeral>10</nova:ephemeral>1818        <nova:vcpus>8</nova:vcpus>1819      </nova:flavor>1820      <nova:owner>1821        <nova:user1822         uuid="3472c2a6-de91-4fb5-b618-42bc781ef670">buzz</nova:user>1823        <nova:project1824         uuid="f241e906-010e-4917-ae81-53f4fb8aa021">moonshot</nova:project>1825      </nova:owner>1826      <nova:root type="image" uuid="fe55c69a-8b2e-4bbc-811a-9ad2023a0426"/>1827    </nova:instance>1828        """)1829class LibvirtConfigGuestIDMap(LibvirtConfigBaseTest):1830    def test_config_id_map_parse_start_not_int(self):1831        xmlin = "<uid start='a' target='20000' count='5'/>"1832        obj = config.LibvirtConfigGuestIDMap()1833        self.assertRaises(ValueError, obj.parse_str, xmlin)1834    def test_config_id_map_parse_target_not_int(self):1835        xmlin = "<uid start='2' target='a' count='5'/>"1836        obj = config.LibvirtConfigGuestIDMap()1837        self.assertRaises(ValueError, obj.parse_str, xmlin)1838    def test_config_id_map_parse_count_not_int(self):1839        xmlin = "<uid start='2' target='20000' count='a'/>"1840        obj = config.LibvirtConfigGuestIDMap()1841        self.assertRaises(ValueError, obj.parse_str, xmlin)1842    def test_config_uid_map(self):1843        obj = config.LibvirtConfigGuestUIDMap()1844        obj.start = 11845        obj.target = 100001846        obj.count = 21847        xml = obj.to_xml()1848        self.assertXmlEqual("<uid start='1' target='10000' count='2'/>", xml)1849    def test_config_uid_map_parse(self):1850        xmlin = "<uid start='2' target='20000' count='5'/>"1851        obj = config.LibvirtConfigGuestUIDMap()1852        obj.parse_str(xmlin)1853        self.assertEqual(2, obj.start)1854        self.assertEqual(20000, obj.target)1855        self.assertEqual(5, obj.count)1856    def test_config_gid_map(self):1857        obj = config.LibvirtConfigGuestGIDMap()1858        obj.start = 11859        obj.target = 100001860        obj.count = 21861        xml = obj.to_xml()1862        self.assertXmlEqual("<gid start='1' target='10000' count='2'/>", xml)1863    def test_config_gid_map_parse(self):1864        xmlin = "<gid start='2' target='20000' count='5'/>"1865        obj = config.LibvirtConfigGuestGIDMap()1866        obj.parse_str(xmlin)1867        self.assertEqual(2, obj.start)1868        self.assertEqual(20000, obj.target)1869        self.assertEqual(5, obj.count)1870class LibvirtConfigMemoryBalloonTest(LibvirtConfigBaseTest):1871    def test_config_memory_balloon_period(self):1872        balloon = config.LibvirtConfigMemoryBalloon()1873        balloon.model = 'fake_virtio'1874        balloon.period = 111875        xml = balloon.to_xml()1876        expected_xml = """1877        <memballoon model='fake_virtio'>1878            <stats period='11'/>1879        </memballoon>"""...test_objects.py
Source:test_objects.py  
...201        for index, item in enumerate(mylist):202            self.assertEqual(db_objs[index]['foo'], item.foo)203            self.assertEqual(db_objs[index]['bar'], item.bar)204            self.assertEqual(db_objs[index]['missing'], item.missing)205def compare_obj(test, obj, db_obj, subs=None, allow_missing=None,206                comparators=None):207    """Compare a NovaObject and a dict-like database object.208    This automatically converts TZ-aware datetimes and iterates over209    the fields of the object.210    :param:test: The TestCase doing the comparison211    :param:obj: The NovaObject to examine212    :param:db_obj: The dict-like database object to use as reference213    :param:subs: A dict of objkey=dbkey field substitutions214    :param:allow_missing: A list of fields that may not be in db_obj215    :param:comparators: Map of comparator functions to use for certain fields216    """217    if subs is None:218        subs = {}219    if allow_missing is None:220        allow_missing = []221    if comparators is None:222        comparators = {}223    for key in obj.fields:224        if key in allow_missing and not obj.obj_attr_is_set(key):225            continue226        obj_val = obj[key]227        db_key = subs.get(key, key)228        db_val = db_obj[db_key]229        if isinstance(obj_val, datetime.datetime):230            obj_val = obj_val.replace(tzinfo=None)231        if key in comparators:232            comparator = comparators[key]233            comparator(db_val, obj_val)234        else:235            test.assertEqual(db_val, obj_val)236class _BaseTestCase(test.TestCase):237    def setUp(self):238        super(_BaseTestCase, self).setUp()239        self.remote_object_calls = list()240        self.context = context.RequestContext('fake-user', 'fake-project')241        fake_notifier.stub_notifier(self.stubs)242        self.addCleanup(fake_notifier.reset)243    def compare_obj(self, obj, db_obj, subs=None, allow_missing=None,244                    comparators=None):245        compare_obj(self, obj, db_obj, subs=subs, allow_missing=allow_missing,246                    comparators=comparators)247    def json_comparator(self, expected, obj_val):248        # json-ify an object field for comparison with its db str249        # equivalent250        self.assertEqual(expected, jsonutils.dumps(obj_val))251    def str_comparator(self, expected, obj_val):252        """Compare an object field to a string in the db by performing253        a simple coercion on the object field value.254        """255        self.assertEqual(expected, str(obj_val))256    def assertNotIsInstance(self, obj, cls, msg=None):257        """Python < v2.7 compatibility.  Assert 'not isinstance(obj, cls)."""258        try:259            f = super(_BaseTestCase, self).assertNotIsInstance...events.js
Source:events.js  
1$(document).ready(function() {2  module("Backbone.Events");3  test("on and trigger", 2, function() {4    var obj = { counter: 0 };5    _.extend(obj,Backbone.Events);6    obj.on('event', function() { obj.counter += 1; });7    obj.trigger('event');8    equal(obj.counter,1,'counter should be incremented.');9    obj.trigger('event');10    obj.trigger('event');11    obj.trigger('event');12    obj.trigger('event');13    equal(obj.counter, 5, 'counter should be incremented five times.');14  });15  test("binding and triggering multiple events", 4, function() {16    var obj = { counter: 0 };17    _.extend(obj, Backbone.Events);18    obj.on('a b c', function() { obj.counter += 1; });19    obj.trigger('a');20    equal(obj.counter, 1);21    obj.trigger('a b');22    equal(obj.counter, 3);23    obj.trigger('c');24    equal(obj.counter, 4);25    obj.off('a c');26    obj.trigger('a b c');27    equal(obj.counter, 5);28  });29  test("binding and triggering with event maps", function() {30    var obj = { counter: 0 };31    _.extend(obj, Backbone.Events);32    var increment = function() {33      this.counter += 1;34    };35    obj.on({36      a: increment,37      b: increment,38      c: increment39    }, obj);40    obj.trigger('a');41    equal(obj.counter, 1);42    obj.trigger('a b');43    equal(obj.counter, 3);44    obj.trigger('c');45    equal(obj.counter, 4);46    obj.off({47      a: increment,48      c: increment49    }, obj);50    obj.trigger('a b c');51    equal(obj.counter, 5);52  });53  test("listenTo and stopListening", 1, function() {54    var a = _.extend({}, Backbone.Events);55    var b = _.extend({}, Backbone.Events);56    a.listenTo(b, 'all', function(){ ok(true); });57    b.trigger('anything');58    a.listenTo(b, 'all', function(){ ok(false); });59    a.stopListening();60    b.trigger('anything');61  });62  test("listenTo and stopListening with event maps", 4, function() {63    var a = _.extend({}, Backbone.Events);64    var b = _.extend({}, Backbone.Events);65    var cb = function(){ ok(true); };66    a.listenTo(b, {event: cb});67    b.trigger('event');68    a.listenTo(b, {event2: cb});69    b.on('event2', cb);70    a.stopListening(b, {event2: cb});71    b.trigger('event event2');72    a.stopListening();73    b.trigger('event event2');74  });75  test("stopListening with omitted args", 2, function () {76    var a = _.extend({}, Backbone.Events);77    var b = _.extend({}, Backbone.Events);78    var cb = function () { ok(true); };79    a.listenTo(b, 'event', cb);80    b.on('event', cb);81    a.listenTo(b, 'event2', cb);82    a.stopListening(null, {event: cb});83    b.trigger('event event2');84    b.off();85    a.listenTo(b, 'event event2', cb);86    a.stopListening(null, 'event');87    a.stopListening();88    b.trigger('event2');89  });90  test("listenToOnce and stopListening", 1, function() {91    var a = _.extend({}, Backbone.Events);92    var b = _.extend({}, Backbone.Events);93    a.listenToOnce(b, 'all', function() { ok(true); });94    b.trigger('anything');95    b.trigger('anything');96    a.listenToOnce(b, 'all', function() { ok(false); });97    a.stopListening();98    b.trigger('anything');99  });100  test("listenTo, listenToOnce and stopListening", 1, function() {101    var a = _.extend({}, Backbone.Events);102    var b = _.extend({}, Backbone.Events);103    a.listenToOnce(b, 'all', function() { ok(true); });104    b.trigger('anything');105    b.trigger('anything');106    a.listenTo(b, 'all', function() { ok(false); });107    a.stopListening();108    b.trigger('anything');109  });110  test("listenTo and stopListening with event maps", 1, function() {111    var a = _.extend({}, Backbone.Events);112    var b = _.extend({}, Backbone.Events);113    a.listenTo(b, {change: function(){ ok(true); }});114    b.trigger('change');115    a.listenTo(b, {change: function(){ ok(false); }});116    a.stopListening();117    b.trigger('change');118  });119  test("listenTo yourself", 1, function(){120    var e = _.extend({}, Backbone.Events);121    e.listenTo(e, "foo", function(){ ok(true); });122    e.trigger("foo");123  });124  test("listenTo yourself cleans yourself up with stopListening", 1, function(){125    var e = _.extend({}, Backbone.Events);126    e.listenTo(e, "foo", function(){ ok(true); });127    e.trigger("foo");128    e.stopListening();129    e.trigger("foo");130  });131  test("listenTo with empty callback doesn't throw an error", 1, function(){132    var e = _.extend({}, Backbone.Events);133    e.listenTo(e, "foo", null);134    e.trigger("foo");135    ok(true);136  });137  test("trigger all for each event", 3, function() {138    var a, b, obj = { counter: 0 };139    _.extend(obj, Backbone.Events);140    obj.on('all', function(event) {141      obj.counter++;142      if (event == 'a') a = true;143      if (event == 'b') b = true;144    })145    .trigger('a b');146    ok(a);147    ok(b);148    equal(obj.counter, 2);149  });150  test("on, then unbind all functions", 1, function() {151    var obj = { counter: 0 };152    _.extend(obj,Backbone.Events);153    var callback = function() { obj.counter += 1; };154    obj.on('event', callback);155    obj.trigger('event');156    obj.off('event');157    obj.trigger('event');158    equal(obj.counter, 1, 'counter should have only been incremented once.');159  });160  test("bind two callbacks, unbind only one", 2, function() {161    var obj = { counterA: 0, counterB: 0 };162    _.extend(obj,Backbone.Events);163    var callback = function() { obj.counterA += 1; };164    obj.on('event', callback);165    obj.on('event', function() { obj.counterB += 1; });166    obj.trigger('event');167    obj.off('event', callback);168    obj.trigger('event');169    equal(obj.counterA, 1, 'counterA should have only been incremented once.');170    equal(obj.counterB, 2, 'counterB should have been incremented twice.');171  });172  test("unbind a callback in the midst of it firing", 1, function() {173    var obj = {counter: 0};174    _.extend(obj, Backbone.Events);175    var callback = function() {176      obj.counter += 1;177      obj.off('event', callback);178    };179    obj.on('event', callback);180    obj.trigger('event');181    obj.trigger('event');182    obj.trigger('event');183    equal(obj.counter, 1, 'the callback should have been unbound.');184  });185  test("two binds that unbind themeselves", 2, function() {186    var obj = { counterA: 0, counterB: 0 };187    _.extend(obj,Backbone.Events);188    var incrA = function(){ obj.counterA += 1; obj.off('event', incrA); };189    var incrB = function(){ obj.counterB += 1; obj.off('event', incrB); };190    obj.on('event', incrA);191    obj.on('event', incrB);192    obj.trigger('event');193    obj.trigger('event');194    obj.trigger('event');195    equal(obj.counterA, 1, 'counterA should have only been incremented once.');196    equal(obj.counterB, 1, 'counterB should have only been incremented once.');197  });198  test("bind a callback with a supplied context", 1, function () {199    var TestClass = function () {200      return this;201    };202    TestClass.prototype.assertTrue = function () {203      ok(true, '`this` was bound to the callback');204    };205    var obj = _.extend({},Backbone.Events);206    obj.on('event', function () { this.assertTrue(); }, (new TestClass));207    obj.trigger('event');208  });209  test("nested trigger with unbind", 1, function () {210    var obj = { counter: 0 };211    _.extend(obj, Backbone.Events);212    var incr1 = function(){ obj.counter += 1; obj.off('event', incr1); obj.trigger('event'); };213    var incr2 = function(){ obj.counter += 1; };214    obj.on('event', incr1);215    obj.on('event', incr2);216    obj.trigger('event');217    equal(obj.counter, 3, 'counter should have been incremented three times');218  });219  test("callback list is not altered during trigger", 2, function () {220    var counter = 0, obj = _.extend({}, Backbone.Events);221    var incr = function(){ counter++; };222    obj.on('event', function(){ obj.on('event', incr).on('all', incr); })223    .trigger('event');224    equal(counter, 0, 'bind does not alter callback list');225    obj.off()226    .on('event', function(){ obj.off('event', incr).off('all', incr); })227    .on('event', incr)228    .on('all', incr)229    .trigger('event');230    equal(counter, 2, 'unbind does not alter callback list');231  });232  test("#1282 - 'all' callback list is retrieved after each event.", 1, function() {233    var counter = 0;234    var obj = _.extend({}, Backbone.Events);235    var incr = function(){ counter++; };236    obj.on('x', function() {237      obj.on('y', incr).on('all', incr);238    })239    .trigger('x y');240    strictEqual(counter, 2);241  });242  test("if no callback is provided, `on` is a noop", 0, function() {243    _.extend({}, Backbone.Events).on('test').trigger('test');244  });245  test("if callback is truthy but not a function, `on` should throw an error just like jQuery", 1, function() {246    var view = _.extend({}, Backbone.Events).on('test', 'noop');247    throws(function() {248      view.trigger('test');249    });250  });251  test("remove all events for a specific context", 4, function() {252    var obj = _.extend({}, Backbone.Events);253    obj.on('x y all', function() { ok(true); });254    obj.on('x y all', function() { ok(false); }, obj);255    obj.off(null, null, obj);256    obj.trigger('x y');257  });258  test("remove all events for a specific callback", 4, function() {259    var obj = _.extend({}, Backbone.Events);260    var success = function() { ok(true); };261    var fail = function() { ok(false); };262    obj.on('x y all', success);263    obj.on('x y all', fail);264    obj.off(null, fail);265    obj.trigger('x y');266  });267  test("#1310 - off does not skip consecutive events", 0, function() {268    var obj = _.extend({}, Backbone.Events);269    obj.on('event', function() { ok(false); }, obj);270    obj.on('event', function() { ok(false); }, obj);271    obj.off(null, null, obj);272    obj.trigger('event');273  });274  test("once", 2, function() {275    // Same as the previous test, but we use once rather than having to explicitly unbind276    var obj = { counterA: 0, counterB: 0 };277    _.extend(obj, Backbone.Events);278    var incrA = function(){ obj.counterA += 1; obj.trigger('event'); };279    var incrB = function(){ obj.counterB += 1; };280    obj.once('event', incrA);281    obj.once('event', incrB);282    obj.trigger('event');283    equal(obj.counterA, 1, 'counterA should have only been incremented once.');284    equal(obj.counterB, 1, 'counterB should have only been incremented once.');285  });286  test("once variant one", 3, function() {287    var f = function(){ ok(true); };288    var a = _.extend({}, Backbone.Events).once('event', f);289    var b = _.extend({}, Backbone.Events).on('event', f);290    a.trigger('event');291    b.trigger('event');292    b.trigger('event');293  });294  test("once variant two", 3, function() {295    var f = function(){ ok(true); };296    var obj = _.extend({}, Backbone.Events);297    obj298      .once('event', f)299      .on('event', f)300      .trigger('event')301      .trigger('event');302  });303  test("once with off", 0, function() {304    var f = function(){ ok(true); };305    var obj = _.extend({}, Backbone.Events);306    obj.once('event', f);307    obj.off('event', f);308    obj.trigger('event');309  });310  test("once with event maps", function() {311    var obj = { counter: 0 };312    _.extend(obj, Backbone.Events);313    var increment = function() {314      this.counter += 1;315    };316    obj.once({317      a: increment,318      b: increment,319      c: increment320    }, obj);321    obj.trigger('a');322    equal(obj.counter, 1);323    obj.trigger('a b');324    equal(obj.counter, 2);325    obj.trigger('c');326    equal(obj.counter, 3);327    obj.trigger('a b c');328    equal(obj.counter, 3);329  });330  test("once with off only by context", 0, function() {331    var context = {};332    var obj = _.extend({}, Backbone.Events);333    obj.once('event', function(){ ok(false); }, context);334    obj.off(null, null, context);335    obj.trigger('event');336  });337  test("Backbone object inherits Events", function() {338    ok(Backbone.on === Backbone.Events.on);339  });340  asyncTest("once with asynchronous events", 1, function() {341    var func = _.debounce(function() { ok(true); start(); }, 50);342    var obj = _.extend({}, Backbone.Events).once('async', func);343    obj.trigger('async');344    obj.trigger('async');345  });346  test("once with multiple events.", 2, function() {347    var obj = _.extend({}, Backbone.Events);348    obj.once('x y', function() { ok(true); });349    obj.trigger('x y');350  });351  test("Off during iteration with once.", 2, function() {352    var obj = _.extend({}, Backbone.Events);353    var f = function(){ this.off('event', f); };354    obj.on('event', f);355    obj.once('event', function(){});356    obj.on('event', function(){ ok(true); });357    obj.trigger('event');358    obj.trigger('event');359  });360  test("`once` on `all` should work as expected", 1, function() {361    Backbone.once('all', function() {362      ok(true);363      Backbone.trigger('all');364    });365    Backbone.trigger('all');366  });367  test("once without a callback is a noop", 0, function() {368    _.extend({}, Backbone.Events).once('event').trigger('event');369  });370  test("event functions are chainable", function() {371    var obj = _.extend({}, Backbone.Events);372    var obj2 = _.extend({}, Backbone.Events);373    var fn = function() {};374    equal(obj, obj.trigger('noeventssetyet'));375    equal(obj, obj.off('noeventssetyet'));376    equal(obj, obj.stopListening('noeventssetyet'));377    equal(obj, obj.on('a', fn));378    equal(obj, obj.once('c', fn));379    equal(obj, obj.trigger('a'));380    equal(obj, obj.listenTo(obj2, 'a', fn));381    equal(obj, obj.listenToOnce(obj2, 'b', fn));382    equal(obj, obj.off('a c'));383    equal(obj, obj.stopListening(obj2, 'a'));384    equal(obj, obj.stopListening());385  });...draggables.js
Source:draggables.js  
1(function (requirejs, require, define) {2define(['js/capa/drag_and_drop/draggable_events', 'js/capa/drag_and_drop/draggable_logic'], function (draggableEvents, draggableLogic) {3    return {4        'init': init5    };6    function init(state) {7        state.config.draggables.every(function (draggable) {8            processDraggable(state, draggable);9            return true;10        });11    }12    function makeDraggableCopy(callbackFunc) {13        var draggableObj, property;14        // Make a full proper copy of the draggable object, with some modifications.15        draggableObj = {};16        for (property in this) {17            if (this.hasOwnProperty(property) === true) {18                draggableObj[property] = this[property];19            }20        }21        // The modifications to the draggable copy.22        draggableObj.isOriginal = false; // This new draggable is a copy.23        draggableObj.uniqueId = draggableObj.state.getUniqueId(); // Is newly set.24        draggableObj.stateDraggablesIndex = null; // Will be set.25        draggableObj.containerEl = null; // Not needed, since a copy will never return to a container element.26        draggableObj.iconEl = null; // Will be created.27        draggableObj.iconImgEl = null; // Will be created.28        draggableObj.labelEl = null; // Will be created.29        draggableObj.targetField = []; // Will be populated.30        // Create DOM elements and attach events.31        if (draggableObj.originalConfigObj.icon.length > 0) {32            draggableObj.iconEl = $('<div></div>');33            draggableObj.iconImgEl = $('<img />');34            draggableObj.iconImgEl.attr('src', draggableObj.originalConfigObj.icon);35            draggableObj.iconImgEl.load(function () {36                draggableObj.iconEl.css({37                    'position': 'absolute',38                    'width': draggableObj.iconWidthSmall,39                    'height': draggableObj.iconHeightSmall,40                    'left': 50 - draggableObj.iconWidthSmall * 0.5,41                    'top': ((draggableObj.originalConfigObj.label.length > 0) ? 5 : 50 - draggableObj.iconHeightSmall * 0.5)42                });43                draggableObj.iconImgEl.css({44                    'position': 'absolute',45                    'width': draggableObj.iconWidthSmall,46                    'height': draggableObj.iconHeightSmall,47                    'left': 0,48                    'top': 049                });50                draggableObj.iconImgEl.appendTo(draggableObj.iconEl);51                if (draggableObj.originalConfigObj.label.length > 0) {52                    draggableObj.labelEl = $(53                        '<div ' +54                            'style=" ' +55                                'position: absolute; ' +56                                'color: black; ' +57                                'font-size: 0.95em; ' +58                            '" ' +59                        'role="label">' +60                            draggableObj.originalConfigObj.label +61                        '</div>'62                    );63                    draggableObj.labelEl.css({64                        'left': 50 - draggableObj.labelWidth * 0.5,65                        'top': 5 + draggableObj.iconHeightSmall + 566                    });67                    draggableObj.attachMouseEventsTo('labelEl');68                }69                draggableObj.attachMouseEventsTo('iconEl');70                draggableObj.stateDraggablesIndex = draggableObj.state.draggables.push(draggableObj) - 1;71                setTimeout(function () {72                    callbackFunc(draggableObj);73                }, 0);74            });75            return;76        } else {77            if (draggableObj.originalConfigObj.label.length > 0) {78                draggableObj.iconEl = $(79                    '<div ' +80                        'style=" ' +81                            'position: absolute; ' +82                            'color: black; ' +83                            'font-size: 0.95em; ' +84                        '" ' +85                    '>' +86                        draggableObj.originalConfigObj.label +87                    '</div>'88                );89                draggableObj.iconEl.css({90                    'left': 50 - draggableObj.iconWidthSmall * 0.5,91                    'top': 50 - draggableObj.iconHeightSmall * 0.592                });93                draggableObj.attachMouseEventsTo('iconEl');94                draggableObj.stateDraggablesIndex = draggableObj.state.draggables.push(draggableObj) - 1;95                setTimeout(function () {96                    callbackFunc(draggableObj);97                }, 0);98                return;99            }100        }101    }102    function processDraggable(state, obj) {103        var draggableObj;104        draggableObj = {105            'uniqueId': state.getUniqueId(),106            'originalConfigObj': obj,107            'stateDraggablesIndex': null,108            'id': obj.id,109            'isReusable': obj.can_reuse,110            'isOriginal': true,111            'x': -1,112            'y': -1,113            'zIndex': 1,114            'containerEl': null,115            'iconEl': null,116            'iconImgEl': null,117            'iconElBGColor': null,118            'iconElPadding': null,119            'iconElBorder': null,120            'iconElLeftOffset': null,121            'iconWidth': null,122            'iconHeight': null,123            'iconWidthSmall': null,124            'iconHeightSmall': null,125            'labelEl': null,126            'labelWidth': null,127            'hasLoaded': false,128            'inContainer': true,129            'mousePressed': false,130            'onTarget': null,131            'onTargetIndex': null,132            'state': state,133            'mouseDown': draggableEvents.mouseDown,134            'mouseUp': draggableEvents.mouseUp,135            'mouseMove': draggableEvents.mouseMove,136            'checkLandingElement': draggableLogic.checkLandingElement,137            'checkIfOnTarget': draggableLogic.checkIfOnTarget,138            'snapToTarget': draggableLogic.snapToTarget,139            'correctZIndexes': draggableLogic.correctZIndexes,140            'moveBackToSlider': draggableLogic.moveBackToSlider,141            'moveDraggableTo': draggableLogic.moveDraggableTo,142            'toggleTargets': draggableLogic.toggleTargets,143            'makeDraggableCopy': makeDraggableCopy,144            'attachMouseEventsTo': draggableEvents.attachMouseEventsTo,145            'targetField': [],146            'numDraggablesOnMe': 0147        };148        draggableObj.containerEl = $(149            '<div ' +150                'style=" ' +151                    'width: 100px; ' +152                    'height: 100px; ' +153                    'display: inline; ' +154                    'float: left; ' +155                    'overflow: hidden; ' +156                    'border-left: 1px solid #CCC; ' +157                    'border-right: 1px solid #CCC; ' +158                    'text-align: center; ' +159                    'position: relative; ' +160                    'cursor: move; ' +161                '" ' +162                'role="listitem"></div>'163        );164        draggableObj.containerEl.appendTo(state.sliderEl);165        if (obj.icon.length > 0) {166            draggableObj.iconElBGColor = 'transparent';167            draggableObj.iconElPadding = 0;168            draggableObj.iconElBorder = 'none';169            draggableObj.iconElLeftOffset = 0;170            draggableObj.iconEl = $('<div></div>');171            draggableObj.iconImgEl = $('<img />');172            draggableObj.iconImgEl.attr('src', obj.icon);173            draggableObj.iconImgEl.load(function () {174                draggableObj.iconWidth = this.width;175                draggableObj.iconHeight = this.height;176                if (draggableObj.iconWidth >= draggableObj.iconHeight) {177                    draggableObj.iconWidthSmall = 60;178                    draggableObj.iconHeightSmall = draggableObj.iconWidthSmall * (draggableObj.iconHeight / draggableObj.iconWidth);179                } else {180                    draggableObj.iconHeightSmall = 60;181                    draggableObj.iconWidthSmall = draggableObj.iconHeightSmall * (draggableObj.iconWidth / draggableObj.iconHeight);182                }183                draggableObj.iconEl.css({184                    'position': 'absolute',185                    'width': draggableObj.iconWidthSmall,186                    'height': draggableObj.iconHeightSmall,187                    'left': 50 - draggableObj.iconWidthSmall * 0.5,188                    // Before:189                    // 'top': ((obj.label.length > 0) ? (100 - draggableObj.iconHeightSmall - 25) * 0.5 : 50 - draggableObj.iconHeightSmall * 0.5)190                    // After:191                    'top': ((obj.label.length > 0) ? 37.5 : 50.0) - 0.5 * draggableObj.iconHeightSmall192                });193                draggableObj.iconImgEl.css({194                    'position': 'absolute',195                    'width': draggableObj.iconWidthSmall,196                    'height': draggableObj.iconHeightSmall,197                    'left': 0,198                    'top': 0199                });200                draggableObj.iconImgEl.appendTo(draggableObj.iconEl);201                draggableObj.iconEl.appendTo(draggableObj.containerEl);202                if (obj.label.length > 0) {203                    draggableObj.labelEl = $(204                        '<div ' +205                            'style=" ' +206                                'position: absolute; ' +207                                'color: black; ' +208                                'font-size: 0.95em; ' +209                                'cursor: move; ' +210                            '" ' +211                        '>' +212                            obj.label +213                        '</div>'214                    );215                    draggableObj.labelEl.appendTo(draggableObj.containerEl);216                    draggableObj.labelWidth = draggableObj.labelEl.width();217                    draggableObj.labelEl.css({218                        'left': 50 - draggableObj.labelWidth * 0.5,219                        // Before:220                        // 'top': (100 - this.iconHeightSmall - 25) * 0.5 + this.iconHeightSmall + 5221                        // After:222                        'top': 42.5 + 0.5 * draggableObj.iconHeightSmall223                    });224                    draggableObj.attachMouseEventsTo('labelEl');225                }226                draggableObj.hasLoaded = true;227            });228        } else {229            // To make life easier, if there is no icon, but there is a230            // label, we will create a label and store it as if it was an231            // icon. All the existing code will work, and the user will232            // see a label instead of an icon.233            if (obj.label.length > 0) {234                draggableObj.iconElBGColor = state.config.labelBgColor;235                draggableObj.iconElPadding = 8;236                draggableObj.iconElBorder = '1px solid black';237                draggableObj.iconElLeftOffset = 9;238                draggableObj.iconEl = $(239                    '<div ' +240                        'style=" ' +241                            'position: absolute; ' +242                            'color: black; ' +243                            'font-size: 0.95em; ' +244                            'cursor: move; ' +245                        '" ' +246                        'tabindex="0" aria-grabbed="false" role="listitem"' +247                    '>' +248                        obj.label +249                    '</div>'250                );251                draggableObj.iconEl.appendTo(draggableObj.containerEl);252                draggableObj.iconWidth = draggableObj.iconEl.width();253                draggableObj.iconHeight = draggableObj.iconEl.height();254                draggableObj.iconWidthSmall = draggableObj.iconWidth;255                draggableObj.iconHeightSmall = draggableObj.iconHeight;256                draggableObj.iconEl.css({257                    'left': 50 - draggableObj.iconWidthSmall * 0.5,258                    'top': 50 - draggableObj.iconHeightSmall * 0.5259                });260                draggableObj.hasLoaded = true;261            } else {262                // If no icon and no label, don't create a draggable.263                return;264            }265        }266        draggableObj.attachMouseEventsTo('iconEl');267        draggableObj.attachMouseEventsTo('containerEl');268        state.numDraggablesInSlider += 1;269        draggableObj.stateDraggablesIndex = state.draggables.push(draggableObj) - 1;270    }271}); // End-of: define(['draggable_events', 'draggable_logic'], function (draggableEvents, draggableLogic) {...ArchProfile.py
Source:ArchProfile.py  
1#***************************************************************************2#*                                                                         *3#*   Copyright (c) 2011                                                    *4#*   Yorik van Havre <yorik@uncreated.net>                                 *5#*                                                                         *6#*   This program is free software; you can redistribute it and/or modify  *7#*   it under the terms of the GNU Lesser General Public License (LGPL)    *8#*   as published by the Free Software Foundation; either version 2 of     *9#*   the License, or (at your option) any later version.                   *10#*   for detail see the LICENCE text file.                                 *11#*                                                                         *12#*   This program is distributed in the hope that it will be useful,       *13#*   but WITHOUT ANY WARRANTY; without even the implied warranty of        *14#*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *15#*   GNU Library General Public License for more details.                  *16#*                                                                         *17#*   You should have received a copy of the GNU Library General Public     *18#*   License along with this program; if not, write to the Free Software   *19#*   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  *20#*   USA                                                                   *21#*                                                                         *22#***************************************************************************23import FreeCAD, Draft, Part, os24from FreeCAD import Vector25import csv26if FreeCAD.GuiUp:27    import FreeCADGui28    from PySide import QtCore, QtGui29    from DraftTools import translate30else:31    def translate(ctxt,txt):32        return txt33__title__="FreeCAD Profile"34__author__ = "Yorik van Havre"35__url__ = "http://www.freecadweb.org"36# Presets in the form: Class, Name, Profile type, [profile data]37# Search for profiles.csv in data/Mod/Arch/Presets and in the same folder as this file38profilefiles = [os.path.join(FreeCAD.getResourceDir(),"Mod","Arch","Presets","profiles.csv"),39                os.path.join(os.path.dirname(__file__),"Presets","profiles.csv")]40def readPresets():41    Presets=[None]42    for profilefile in profilefiles:43        if os.path.exists(profilefile):44            try:45                with open(profilefile, 'rb') as csvfile:46                    beamreader = csv.reader(csvfile)47                    bid=1 #Unique index48                    for row in beamreader:49                        if row[0].startswith("#"):50                            continue51                        try:52                            r=[bid, row[0], row[1], row[2]]53                            for i in range(3,len(row)):54                                r=r+[float(row[i])]55                            if not r in Presets:56                                Presets.append(r)57                            bid=bid+158                        except ValueError:59                            print "Skipping bad line: "+str(row)60            except IOError:61                print "Could not open ",profilefile62    return Presets63def makeProfile(profile=[0,'REC','REC100x100','R',100,100]):64    '''makeProfile(profile): returns a shape  with the face defined by the profile data'''65    obj = FreeCAD.ActiveDocument.addObject("Part::Part2DObjectPython",profile[2])66    obj.Label = translate("Arch",profile[2])67    if profile[3]=="C":68        _ProfileC(obj, profile)69    elif profile[3]=="H":70        _ProfileH(obj, profile)71    elif profile[3]=="R":72        _ProfileR(obj, profile)73    elif profile[3]=="RH":74        _ProfileRH(obj, profile)75    elif profile[3]=="U":76        _ProfileU(obj, profile)77    else :78        print "Profile not supported"79    if FreeCAD.GuiUp:80        Draft._ViewProviderDraft(obj.ViewObject)81    return obj82class _Profile(Draft._DraftObject):83    '''Superclass for Profile classes'''84    def __init__(self,obj, profile):85        self.Profile=profile86        Draft._DraftObject.__init__(self,obj,"Profile")87        88            89class _ProfileC(_Profile):90    '''A parametric circular tubeprofile. Profile data: [Outside diameter, Inside diameter]'''91    def __init__(self,obj, profile):92        obj.addProperty("App::PropertyLength","OutDiameter","Draft","Outside Diameter").OutDiameter = profile[4]93        obj.addProperty("App::PropertyLength","Thickness","Draft","Wall thickness").Thickness = profile[5]94        _Profile.__init__(self,obj,profile)95    def execute(self,obj):96        pl = obj.Placement97        c1=Part.Circle()98        c1.Radius=obj.OutDiameter.Value99        c2=Part.Circle()100        c2.Radius=obj.OutDiameter.Value-2*obj.Thickness.Value101        cs1=c1.toShape()102        cs2=c2.toShape()103        p=Part.makeRuledSurface(cs2,cs1)104        obj.Shape = p105        obj.Placement = pl106        107class _ProfileH(_Profile):108    '''A parametric H or I beam profile. Profile data: [width, height, web thickness, flange thickness] (see http://en.wikipedia.org/wiki/I-beam for reference)'''109    def __init__(self,obj, profile):110        obj.addProperty("App::PropertyLength","Width","Draft","Width of the beam").Width = profile[4]111        obj.addProperty("App::PropertyLength","Height","Draft","Height of the beam").Height = profile[5]112        obj.addProperty("App::PropertyLength","WebThickness","Draft","Thickness of the web").WebThickness = profile[6]113        obj.addProperty("App::PropertyLength","FlangeThickness","Draft","Thickness of the flanges").FlangeThickness = profile[7]114        _Profile.__init__(self,obj,profile)115    def execute(self,obj):116        pl = obj.Placement117        p1 = Vector(-obj.Width.Value/2,-obj.Height.Value/2,0)118        p2 = Vector(obj.Width.Value/2,-obj.Height.Value/2,0)119        p3 = Vector(obj.Width.Value/2,(-obj.Height.Value/2)+obj.FlangeThickness.Value,0)120        p4 = Vector(obj.WebThickness.Value/2,(-obj.Height.Value/2)+obj.FlangeThickness.Value,0)121        p5 = Vector(obj.WebThickness.Value/2,obj.Height.Value/2-obj.FlangeThickness.Value,0)122        p6 = Vector(obj.Width.Value/2,obj.Height.Value/2-obj.FlangeThickness.Value,0)123        p7 = Vector(obj.Width.Value/2,obj.Height.Value/2,0)124        p8 = Vector(-obj.Width.Value/2,obj.Height.Value/2,0)125        p9 = Vector(-obj.Width.Value/2,obj.Height.Value/2-obj.FlangeThickness.Value,0)126        p10 = Vector(-obj.WebThickness.Value/2,obj.Height.Value/2-obj.FlangeThickness.Value,0)127        p11 = Vector(-obj.WebThickness.Value/2,(-obj.Height.Value/2)+obj.FlangeThickness.Value,0)128        p12 = Vector(-obj.Width.Value/2,(-obj.Height.Value/2)+obj.FlangeThickness.Value,0)129        p = Part.makePolygon([p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11,p12,p1])130        p = Part.Face(p)131        p.reverse()132        obj.Shape = p133        obj.Placement = pl134class _ProfileR(_Profile):135    '''A parametric rectangular beam profile based on [Width, Height]'''136    def __init__(self,obj, profile):137        obj.addProperty("App::PropertyLength","Width","Draft","Width of the beam").Width = profile[4]138        obj.addProperty("App::PropertyLength","Height","Draft","Height of the beam").Height = profile[5]139        _Profile.__init__(self,obj,profile)140    def execute(self,obj):141        pl = obj.Placement142        p1 = Vector(-obj.Width.Value/2,-obj.Height.Value/2,0)143        p2 = Vector(obj.Width.Value/2,-obj.Height.Value/2,0)144        p3 = Vector(obj.Width.Value/2,obj.Height.Value/2,0)145        p4 = Vector(-obj.Width.Value/2,obj.Height.Value/2,0)146        p = Part.makePolygon([p1,p2,p3,p4,p1])147        p = Part.Face(p)148        p.reverse()149        obj.Shape = p150        obj.Placement = pl151class _ProfileRH(_Profile):152    '''A parametric Rectangular hollow beam profile. Profile data: [width, height, thickness]'''153    def __init__(self,obj, profile):154        obj.addProperty("App::PropertyLength","Width","Draft","Width of the beam").Width = profile[4]155        obj.addProperty("App::PropertyLength","Height","Draft","Height of the beam").Height = profile[5]156        obj.addProperty("App::PropertyLength","Thickness","Draft","Thickness of the sides").Thickness = profile[6]157        _Profile.__init__(self,obj,profile)158    def execute(self,obj):159        pl = obj.Placement160        p1 = Vector(-obj.Width.Value/2,-obj.Height.Value/2,0)161        p2 = Vector(obj.Width.Value/2,-obj.Height.Value/2,0)162        p3 = Vector(obj.Width.Value/2,obj.Height.Value/2,0)163        p4 = Vector(-obj.Width.Value/2,obj.Height.Value/2,0)164        q1 = Vector(-obj.Width.Value/2+obj.Thickness.Value,-obj.Height.Value/2+obj.Thickness.Value,0)165        q2 = Vector(obj.Width.Value/2-obj.Thickness.Value,-obj.Height.Value/2+obj.Thickness.Value,0)166        q3 = Vector(obj.Width.Value/2-obj.Thickness.Value,obj.Height.Value/2-obj.Thickness.Value,0)167        q4 = Vector(-obj.Width.Value/2+obj.Thickness.Value,obj.Height.Value/2-obj.Thickness.Value,0)168        p = Part.makePolygon([p1,p2,p3,p4,p1])169        q = Part.makePolygon([q1,q2,q3,q4,q1])170        r = Part.Face([p,q])171        r.reverse()172        obj.Shape = r173        obj.Placement = pl174        175class _ProfileU(_Profile):176    '''A parametric H or I beam profile. Profile data: [width, height, web thickness, flange thickness] (see  http://en.wikipedia.org/wiki/I-beam forreference)'''177    def __init__(self,obj, profile):178        obj.addProperty("App::PropertyLength","Width","Draft","Width of the beam").Width = profile[4]179        obj.addProperty("App::PropertyLength","Height","Draft","Height of the beam").Height = profile[5]180        obj.addProperty("App::PropertyLength","WebThickness","Draft","Thickness of the webs").WebThickness = profile[6]181        obj.addProperty("App::PropertyLength","FlangeThickness","Draft","Thickness of the flange").FlangeThickness = profile[7]182        _Profile.__init__(self,obj,profile)183    def execute(self,obj):184        pl = obj.Placement185        p1 = Vector(-obj.Width.Value/2,-obj.Height.Value/2,0)186        p2 = Vector(obj.Width.Value/2,-obj.Height.Value/2,0)187        p3 = Vector(obj.Width.Value/2,obj.Height.Value/2,0)188        p4 = Vector(obj.Width.Value/2-obj.FlangeThickness.Value,obj.Height.Value/2,0)189        p5 = Vector(obj.Width.Value/2-obj.FlangeThickness.Value,obj.WebThickness.Value-obj.Height.Value/2,0)190        p6 = Vector(-obj.Width.Value/2+obj.FlangeThickness.Value,obj.WebThickness.Value-obj.Height.Value/2,0)191        p7 = Vector(-obj.Width.Value/2+obj.FlangeThickness.Value,obj.Height.Value/2,0)192        p8 = Vector(-obj.Width.Value/2,obj.Height.Value/2,0)193        p = Part.makePolygon([p1,p2,p3,p4,p5,p6,p7,p8,p1])194        p = Part.Face(p)195        p.reverse()196        obj.Shape = p197        obj.Placement = pl...locpick.js
Source:locpick.js  
1/**2 * @file3 * Location chooser interface.4 */5/*global $, Drupal, google.maps */6(function ($) {7    Drupal.gmap.addHandler('gmap', function (elem) {8        var obj = this;9        var binding = obj.bind("locpickchange", function (position) {10            if (position && position.lat) { // you passed a valid position11                obj.locpick_coord = position;12                obj.locpick_invalid = false;13            }14            obj.locpick_invalid = !(obj.locpick_coord && obj.locpick_coord.lat);// has a proper coord has been set since we last checked15            if (obj.locpick_invalid) {16                return; // invalid coord17            }18            if (!obj.locpick_point) {19                obj.locpick_point = new google.maps.Marker({ // should we use obj.bind('addmarker',-1,{position:obj.locpick_coord}); ?20                    position: obj.locpick_coord,21                    map: obj.map,22                    draggable: true23                });24                google.maps.event.addListener(obj.locpick_point, 'drag', function () {25                    obj.locpick_coord = new google.maps.LatLng(obj.locpick_point.getPosition().lat(), obj.locpick_point.getPosition().lng());26                    obj.change('locpickchange', binding);27                });28                google.maps.event.addListener(obj.locpick_point, 'dragend', function () {29                    obj.locpick_coord = new google.maps.LatLng(obj.locpick_point.getPosition().lat(), obj.locpick_point.getPosition().lng());30                    obj.change('locpickchange', binding);31                });32                obj.map.panTo(obj.locpick_coord);33                obj.change('locpickchange', binding);34            }35            else {36                obj.locpick_point.setPosition(obj.locpick_coord);37            }38        });39        obj.bind("locpickremove", function () {40            if (obj.locpick_point) obj.locpick_point.setMap(null);41            obj.locpick_point = null;42            obj.locpick_coord = null;43            obj.change('locpickchange', -1);44        });45        obj.bind("init", function () {46            if (obj.vars.behavior.locpick) {47                obj.locpick_coord = new google.maps.LatLng(obj.vars.latitude, obj.vars.longitude);48                google.maps.event.addListener(obj.map, "click", function (event) {49                    google.maps.event.trigger(obj.map, "resize");50                    if (event) {51                        obj.locpick_coord = event.latLng;52                        obj.change('locpickchange');53                    }54                    else {55                        // Unsetting the location56                        obj.change('locpickremove');57                    }58                });59            }60        });61        obj.bind("ready", function () {62            // Fake a click to set the initial point, if one was set.63            if (obj.vars.behavior.locpick) {64                if (!obj.locpick_invalid) {65                    obj.change('locpickchange');66                }67            }68        });69    });70    Drupal.gmap.addHandler('locpick_latitude', function (elem) {71        var obj = this;72        obj.bind("init", function () {73            if (elem.value !== '') {74                obj.vars.latitude = Number(elem.value);75                obj.locpick_coord = new google.maps.LatLng(obj.vars.latitude, obj.vars.longitude);76            }77            else {78                obj.locpick_coord = null;79                obj.locpick_invalid = true;80            }81        });82        var binding = obj.bind("locpickchange", function () {83            if (obj.locpick_coord) {84                elem.value = obj.locpick_coord.lat();85            }86            else {87                elem.value = '';88            }89        });90        $(elem).change(function () {91            if (elem.value !== '') {92                if (obj.locpick_coord) {93                    obj.locpick_coord = new google.maps.LatLng(Number(elem.value), obj.locpick_coord.lng());94                    obj.change('locpickchange', binding);95                }96                else {97                    obj.locpick_coord = new google.maps.LatLng(Number(elem.value), 0.0);98                }99            }100            else {101                obj.change('locpickremove', -1);102            }103        });104    });105    Drupal.gmap.addHandler('locpick_longitude', function (elem) {106        var obj = this;107        obj.bind("init", function () {108            if (elem.value !== '') {109                obj.vars.longitude = Number(elem.value);110                //obj.locpick_coord = new GLatLng(obj.vars.latitude, obj.vars.longitude);111                obj.locpick_coord = new google.maps.LatLng(obj.vars.latitude, obj.vars.longitude);112            }113            else {114                obj.locpick_invalid = true;115            }116        });117        var binding = obj.bind("locpickchange", function () {118            if (obj.locpick_coord) {119                elem.value = obj.locpick_coord.lng();120            }121            else {122                elem.value = '';123            }124        });125        $(elem).change(function () {126            if (elem.value !== '') {127                if (obj.locpick_coord) {128                    obj.locpick_coord = new google.maps.LatLng(obj.locpick_coord.lat(), Number(elem.value));129                    obj.change('locpickchange', binding);130                }131                else {132                    obj.locpick_coord = new google.maps.LatLng(0.0, Number(elem.value));133                }134            }135            else {136                obj.change('locpickremove');137            }138        });139    });...events-dynamic.js
Source:events-dynamic.js  
1/**2 * Event Date and Time Dynamic Helper Text3 *4 * @var object tribe_dynamic_helper_text5 */6var tribe_dynamic_helper_text = tribe_dynamic_helper_text || {};7(function ( $, obj ) {8	'use strict';9	obj.field_class       = '.event-dynamic-helper-text';10	obj.date_fmt_settings = {11		dateSettings : {12			days        : tribe_dynamic_help_text.days,13			daysShort   : tribe_dynamic_help_text.daysShort,14			months      : tribe_dynamic_help_text.months,15			monthsShort : tribe_dynamic_help_text.monthsShort,16		}17	};18	obj.date_fmt = new DateFormatter( obj.date_fmt_settings );19	obj.text     = JSON.parse( tribe_dynamic_help_text.msgs );20	// Date Formats21	obj.date_with_year    = tribe_dynamic_help_text.date_with_year;22	obj.date_no_year      = tribe_dynamic_help_text.date_no_year;23	obj.datepicker_format = tribe_dynamic_help_text.datepicker_format;24	// Setup object variables25	obj.dynamic_text, obj.start_date, obj.start_time, obj.end_date, obj.end_time, obj.all_day = '';26	/**27	 * Setup Dynamic Text on Load28	 */29	obj.init = function () {30		//setup text and display31		obj.setup_and_display_text();32		//detect event date & time changes33		obj.event_date_change();34	};35	/**36	 * Wrapper Method to call methods to update and display text37	 */38	obj.setup_and_display_text = function () {39		//get current field values40		obj.update();41		//determine message to use based on values42		obj.msg_logic();43		//parse the message and insert into dymanic text div44		obj.parse_and_display_text();45	};46	/**47	 * Get Event Date and Time Values48	 */49	obj.update = function () {50		obj.start_date = $( '#EventStartDate' ).val();51		obj.start_time = $( '#EventStartTime' ).val();52		obj.end_date   = $( '#EventEndDate' ).val();53		obj.end_time   = $( '#EventEndTime' ).val();54		obj.all_day    = $( '#allDayCheckbox' ).prop( 'checked' ) ? true : '';55		// Prevent user from making an invalid end-time entry; an event has to end after it starts, not before.56		if ( obj.start_date === obj.end_date ) {57			// Convert to 24-hour time for easier comparison.58			var comparison_start_time = moment( obj.start_time, 'h:mm a' ).format( 'HH:mm' );59			var comparison_end_time   = moment( obj.end_time, 'h:mm a' ).format( 'HH:mm' );60			if ( comparison_start_time > comparison_end_time ) {61				if ( 'undefined' !== typeof $.fn.tribeTimepicker ) {62					$( '#EventEndTime' ).tribeTimepicker( 'setTime', obj.start_time );63				} else {64					// @deprecated 4.6.165					$( '#EventEndTime' ).timepicker( 'setTime', obj.start_time );66				}67				obj.end_time = obj.start_time;68			}69		}70	};71	/**72	 * Determine Message to Use based on Date and Time73	 */74	obj.msg_logic = function () {75		if ( obj.start_date == obj.end_date && !obj.all_day && obj.start_time != obj.end_time ) {76			//single date, different start and end time77			obj.dynamic_text = obj.text[0];78		} else if ( obj.start_date == obj.end_date && !obj.all_day && obj.start_time == obj.end_time ) {79			//single date, same start and end time80			obj.dynamic_text = obj.text[1];81		} else if ( obj.start_date == obj.end_date && obj.all_day ) {82			//single date, all day83			obj.dynamic_text = obj.text[2];84		} else if ( obj.start_date != obj.end_date && !obj.all_day && obj.start_time != obj.end_time ) {85			//different date, different start and end time86			obj.dynamic_text = obj.text[3];87		} else if ( obj.start_date != obj.end_date && !obj.all_day && obj.start_time == obj.end_time ) {88			//different date, same start and end time89			obj.dynamic_text = obj.text[4];90		} else if ( obj.start_date != obj.end_date && obj.all_day ) {91			//different date, all day92			obj.dynamic_text = obj.text[5];93		}94	};95	/**96	 * Parse the Message and Insert into Div97	 */98	obj.parse_and_display_text = function () {99		obj.dynamic_text = obj.dynamic_text.replace( "%%starttime%%", obj.start_time );100		obj.dynamic_text = obj.dynamic_text.replace( "%%endtime%%", obj.end_time );101		obj.dynamic_text = obj.dynamic_text.replace( "%%startdatewithyear%%", obj.date_formatter( obj.start_date, obj.datepicker_format, obj.date_with_year ) );102		obj.dynamic_text = obj.dynamic_text.replace( "%%enddatewithyear%%", obj.date_formatter( obj.end_date, obj.datepicker_format, obj.date_with_year ) );103		obj.dynamic_text = obj.dynamic_text.replace( "%%startdatenoyear%%", obj.date_formatter( obj.start_date, obj.datepicker_format, obj.date_no_year ) );104		obj.dynamic_text = obj.dynamic_text.replace( "%%enddatenoyear%%", obj.date_formatter( obj.end_date, obj.datepicker_format, obj.date_no_year ) );105		$( obj.field_class ).html( obj.dynamic_text );106	};107	/**108	 * Format Date using DateFormatter library enabling PHP date-time formats109	 *110	 * @param date111	 * @param datepicker112	 * @param dateformat113	 * @returns {*}114	 */115	obj.date_formatter = function ( date, datepicker, dateformat ) {116		return obj.date_fmt.formatDate( obj.date_fmt.parseDate( date, datepicker ), dateformat );117	};118	/**119	 * Detect Changes to Event Start and End Dates, and All Day Checkbox120	 */121	obj.event_date_change = function () {122		$( '#EventStartDate, #EventStartTime, #EventEndDate, #EventEndTime, #allDayCheckbox' ).on( 'change', function () {123			obj.setup_and_display_text();124		} );125	};126	/**127	 * Init Dynamic Help if on Single Event Editor128	 */129	$( function () {130		if ( $( '#eventDetails, #event_datepickers' ).hasClass( 'eventForm' ) ) {131			obj.init();132		}133	} );...Using AI Code Generation
1var mb = require('mountebank');2var port = 2525;3var imposter = {4        {5                {6                    is: {7                        headers: {8                        },9                        body: JSON.stringify(10                            {11                            }12                    }13                }14        }15};16mb.create(imposter).then(function () {17    console.log('Imposter created at port ' + port);18});Using AI Code Generation
1var mb = require('mountebank');2var http = require('http');3var assert = require('assert');4var fs = require('fs');5var path = require('path');6var url = require('url');7var request = require('request');8var Q = require('q');9var cp = require('child_process');10var imposters = 0;11var imposterPort = 0;12var imposterUrl = '';13var imposterProtocol = '';14var imposterName = '';15var imposterStub = '';16var imposterStubPredicate = '';17var imposterStubResponse = '';18var imposterStubResponseStatusCode = 0;19var imposterStubResponseHeaders = '';20var imposterStubResponseBody = '';21var imposterStubResponseIs = '';22var imposterStubResponseIsText = '';23var imposterStubResponseIsJson = '';24var imposterStubResponseIsJsonKey = '';25var imposterStubResponseIsJsonValue = '';26var imposterStubResponseIsJsonKey1 = '';27var imposterStubResponseIsJsonKey2 = '';28var imposterStubResponseIsJsonValue1 = '';29var imposterStubResponseIsJsonKey3 = '';30var imposterStubResponseIsJsonValue2 = '';31var imposterStubResponseIsJsonKey4 = '';32var imposterStubResponseIsJsonValue3 = '';33var imposterStubResponseIsJsonKey5 = '';34var imposterStubResponseIsJsonValue4 = '';35var imposterStubResponseIsJsonKey6 = '';36var imposterStubResponseIsJsonValue5 = '';37var imposterStubResponseIsJsonKey7 = '';38var imposterStubResponseIsJsonValue6 = '';39var imposterStubResponseIsJsonKey8 = '';40var imposterStubResponseIsJsonValue7 = '';41var imposterStubResponseIsJsonKey9 = '';42var imposterStubResponseIsJsonValue8 = '';43var imposterStubResponseIsJsonKey10 = '';44var imposterStubResponseIsJsonValue9 = '';45var imposterStubResponseIsJsonKey11 = '';Using AI Code Generation
1const mb = require('mountebank');2const Imposter = mb.Imposter;3const Predicate = mb.Predicate;4const Response = mb.Response;5const Stub = mb.Stub;6const imposter = Imposter.create(25, 'http');7const predicate = Predicate.create({method: 'GET', path: '/test'});8const response = Response.create({statusCode: 200, body: 'Hello World'});9const stub = Stub.create({predicates: [predicate], responses: [response]});10imposter.addStub(stub);11mb.post(imposter).then(function (imposter) {12    console.log('imposter created');13});14mb.del(imposter.port).then(function () {15    console.log('imposter deleted');16});17mb.delAll().then(function () {18    console.log('all imposters deleted');19});20mb.get().then(function (imposters) {21    console.log('all imposters retrieved');22});23mb.get(imposter.port).then(function (imposter) {24    console.log('imposter retrieved');25});26mb.get(imposter.port).then(function (imposter) {27    console.log('imposter retrieved');28});29const imposter = Imposter.create(25, 'http');30const predicate = Predicate.create({method: 'GET', path: '/test'});31const response = Response.create({statusCode: 200, body: 'Hello World'});32const stub = Stub.create({predicates: [predicate], responses: [response]});Using AI Code Generation
1var mb = require('mountebank');2var imposter = {3    stubs: [{4        responses: [{5            is: {6            }7        }]8    }]9};10mb.create(imposter).then(function () {11    console.log('Imposter created');12});13{14    "scripts": {15    },16    "dependencies": {17    }18}19var mb = require('mountebank');20var imposter = {21    stubs: [{22        responses: [{23            is: {24            }25        }]26    }]27};28mb.create(imposter).then(function () {29    console.log('Imposter created');30    setTimeout(function(){31        mb.del(8080);32        console.log('Imposter deleted');33    }, 10000);34});Using AI Code Generation
1var mb = require('mountebank');2var http = require('http');3var assert = require('assert');4var fs = require('fs');5var path = require('path');6var util = require('util');7var child_process = require('child_process');8var Q = require('q');9var _ = require('underscore');Using AI Code Generation
1const obj = require('mountebank');2obj.create({3});4obj.stop();5const obj = require('mountebank');6obj.create({7});8obj.stop();9const obj = require('mountebank');10obj.create({11});12obj.stop();13const obj = require('mountebank');14obj.create({15});16obj.stop();17const obj = require('mountebank');18obj.create({19});20obj.stop();21const obj = require('mountebank');22obj.create({23});24obj.stop();25const obj = require('mountebank');26obj.create({Using AI Code Generation
1const mb = require('mountebank');2const fs = require('fs');3const path = require('path');4const axios = require('axios');5const chai = require('chai');6const expect = chai.expect;7const chaiJsonSchema = require('chai-json-schema');8const jsonschema = require('jsonschema');9const jsonSchemaRefParser = require('json-schema-ref-parser');10const faker = require('faker');11const uuid = require('uuid');12const _ = require('lodash');13const moment = require('moment');14const async = require('async');15const Promise = require('bluebird');16const request = require('request');17const requestPromise = require('request-promise');18const supertest = require('supertest');19const chaiHttp = require('chai-http');20const cheerio = require('cheerio');21const jsdom = require('jsdom');22const cheerioHttpcli = require('cheerio-httpcli');23const puppeteer = require('puppeteer');24const webdriver = require('selenium-webdriver');25const webdriverio = require('webdriverio');26const protractor = require('protractor');27const jasmine = require('jasmine');28const mocha = require('mocha');29const chai = require('chai');Using AI Code Generation
1const mb = require('mountebank');2const imposters = require('./imposters.json');3const port = 2525;4const protocol = 'http';5const path = '/imposters';6const options = {7  headers: {8  }9};10const req = http.request(options, (res) => {11  res.setEncoding('utf8');12  res.on('data', (chunk) => {13    console.log(chunk);14  });15});16req.on('error', (e) => {17  console.log('problem with request: ' + e.message);18});19req.write(JSON.stringify(imposters));20req.end();21  {22      {23          {24            "is": {25              "headers": {26              },27              "body": {28              }29            }30          }31      }32  }33{34  "scripts": {35  },36  "dependencies": {37  }38}39  {40      {41          {42            "is": {43              "headers": {44              },45              "body": {46              }47            }48          }49      }50  }51const mb = require('mountebank');52const imposters = require('./imposters.json');Using AI Code Generation
1var mb = require('mountebank');2var server = mb.create();3server.then(function (s) {4    var stub = {5        predicates: [{equals: {path: '/test'}}],6        responses: [{is: {statusCode: 200, body: 'Hello World'}}]7    };8    return s.post('/imposters', {protocol: 'http', port: 3000, stubs: [stub]});9}).then(function (response) {10    console.log(response.body);11});12var mb = require('mountebank');13var server = mb.create();14server.then(function (s) {15    var stub = {16        predicates: [{equals: {path: '/test'}}],17        responses: [{is: {statusCode: 200, body: 'Hello World'}}]18    };19    return s.post('/imposters', {protocol: 'http', port: 3000, stubs: [stub]});20}).then(function (response) {21    console.log(response.body);22});23var mb = require('mountebank');24var server = mb.create();25server.then(function (s) {26    var stub = {27        predicates: [{equals: {path: '/test'}}],28        responses: [{is: {statusCode: 200, body: 'Hello World'}}]29    };30    return s.post('/imposters', {protocol: 'http', port: 3000, stubs: [stub]});31}).then(function (response) {32    console.log(response.body);33});34var mb = require('mountebank');35var server = mb.create();36server.then(function (s) {37    var stub = {38        predicates: [{equals: {path: '/test'}}],39        responses: [{is: {statusCode: 200, body: 'Hello World'}}]40    };Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
