Exemples d’utilisation de TDConnection
Cette section fournit plusieurs exemples de scripts de projet pour vous aider à comprendre comment utiliser l’objet TDConnection.
Dans cette rubrique :
- Exemple : Rejeter une anomalie et la convertir en exigence
- Exemple : Envoyer une anomalie par e-mail
- Exemple : Filtrer les enregistrements
- Exemple : Télécharger un fichier à partir d’un objet en pièce jointe
- Exemple : Obtenir et définir les propriétés des anomalies
- Exemple : Créer des liens entre les anomalies
- Exemple : Renseigner le cycle des releases cibles dans les enfants
- Exemple : Déplacer des exigences
- Exemple : Récupérer des exigences triées
- Exemple : Obtenir les tests de couverture non exécutés
Exemple : Rejeter une anomalie et la convertir en exigence
Cet exemple illustre le cas d’utilisation suivant :
Lorsqu’une anomalie est rejetée avec le motif « Convertir en BLI », une exigence est automatiquement créée et liée à l’anomalie.
var BUG_STATUS = "BG_STATUS";
var BUG_REJECT_REASON = "BG_USER_01";
var BUG_CONVERTED_BLI_FOLDER_ID = 1;
async function Bug_FieldChange(fieldName) {
if (fieldName === BUG_STATUS) {
var status = Bug_Fields(BUG_STATUS).Value;
if (status === "Rejected") {
Bug_Fields(BUG_REJECT_REASON).IsRequired = true;
} else {
Bug_Fields(BUG_REJECT_REASON).IsRequired = false;
}
return;
}
if (fieldName === BUG_REJECT_REASON) {
var rejectReason = Bug_Fields(BUG_REJECT_REASON).Value;
if (rejectReason !== "Converted to BLI") return;
var isCreateBli = await MsgBox("Do you want to create a bli which links to this defect?", 1);
if (!isCreateBli) return;
try {
// Create requirement
var reqFactory = TDConnection.ReqFactory;
var reqItem = reqFactory.AddItem(null);
reqItem.Name = "Converted BLI from defect " + Bug_Fields("BG_BUG_ID").Value + ": " + Bug_Fields("BG_SUMMARY").Value;
reqItem.ParentId = BUG_CONVERTED_BLI_FOLDER_ID;
reqItem.Post();
// Create linkage
var linkFactory = reqItem.BugLinkFactory;
linkFactory.AddItem(Bug_Fields("BG_BUG_ID").Value);
var comments = Bug_Fields("BG_DEV_COMMENTS").Value;
if (comments) {
comments += "\n\n";
} else {
comments = "";
}
comments += (User.UserName + ", " + (new Date).toLocaleDateString() + ": Converted to bli " + reqItem.ID);
Bug_Fields("BG_DEV_COMMENTS").Value = comments;
} catch (e) {
debugger;
}
}
}
Exemple : Envoyer une anomalie par e-mail
Le script suivant envoie l’anomalie avec l’ID 1 par e-mail. Les pièces jointes et l’historique des anomalies sont également inclus dans l’e-mail. L’email est envoyé avec la mention Importance haute.
var bug = TDConnection.BugFactory.Item(1)
bug.Mail(
"abc@vip.com,123@vip.com,xyz@vip.com",
"ccrecipient@vip.com",
"bccrecipient@vip.com",
1 | 2 , // Send the entity's attachments and include the entity's history in this mail
"This is the email subject line.",
1, // Set the priority as high
"This is the email comment"
)
Exemple : Filtrer les enregistrements
Filtrer les anomalies
function bugFilter() {
try {
const bugFactory = TDConnection.BugFactory;
const bugFilter = bugFactory.Filter;
// Set the filter values
bugFilter.Filter["BG_STATUS"] = "Closed";
bugFilter.Order["BG_PRIORITY"] = 1;
console.log(bugFilter.Text); // Output the filter text
// Create a list of defects from the filter and show a few of them
const bugList = bugFilter.NewList();
let msg = `Number of defects = ${bugList.length}\n`;
let count = 0;
for (const theBug of bugList) {
msg += `${theBug.ID}, ${theBug.Summary}, ${theBug.Status}, ${theBug.Priority}\n`;
count++;
if (count > 10) break; // Limiting to the first 10 bugs
}
// Display the message in a dialog box
MsgBox(msg);
} catch (error) {
console.error("Error in bugFilter:", error);
}
}
Filtrer les exigences par type
function filterReqsByType() {
try {
const reqFactory = TDConnection.ReqFactory;
const filter = reqFactory.Filter;
// Use requirement type ID to fetch requirements of a specific type.
filter.Filter["RQ_TYPE_ID"] = 101;
const reqList = filter.NewList();
// Print out each requirement's details
reqList.forEach((req) => {
console.log(`${req.Name} : ${req.TypeId} : ${req.RequirementType.Name}`);
});
} catch (error) {
console.error("Error in filterReqsByType:", error);
}
}
Exemple : Télécharger un fichier à partir d’un objet en pièce jointe
function attachmentDownload() {
try {
// Get the BugFactory from the global TDConnection object
let bugFact = TDConnection.BugFactory;
// Retrieve a specific bug object by ID (in this case, ID 1)
let bugObj = bugFact.Item(1);
console.log(bugObj.Summary); // Log the bug summary for reference
// Access the attachments associated with the bug object
let attachFact = bugObj.Attachments;
// Create a new list of attachments
let attachList = attachFact.NewList("");
if (attachList.length === 0) return;
// Get the first attachment from the attachment list
let attachObj = attachList[0];
console.log(attachObj.FileName); // Log the file name of the attachment
// Load the attachment
attachObj.Load();
console.log(`Attachment downloaded);
// Return success status
return "SUCCESS";
} catch (err) {
return "FAILURE"; // Return failure status
}
}
Exemple : Obtenir et définir les propriétés des anomalies
function bugProperties(theBug) {
try {
// Print the properties.
console.log("Initial Bug properties");
console.log(theBug.Priority);
console.log(theBug.AssignedTo);
console.log(theBug.DetectedBy);
console.log(theBug.Status);
console.log(theBug.Summary);
// Change the values.
theBug.Priority = "4-Very High";
theBug.AssignedTo = "steves";
theBug.DetectedBy = "alex_alm";
theBug.Status = "Fixed";
theBug.Summary = "Amended: The list of flights is given even when past date set as Departing date";
// Commit to database.
theBug.Post();
// Check the new values.
console.log("Changed Bug properties");
console.log(theBug.Priority);
console.log(theBug.AssignedTo);
console.log(theBug.DetectedBy);
console.log(theBug.Status);
console.log(theBug.Summary);
return "SUCCESS";
} catch (err) {
return "FAILURE";
}
}
Exemple : Créer des liens entre les anomalies
async function linkDefects() {
try {
const bugF = TDConnection.BugFactory;
// Create the first bug
const bug1 = bugF.AddItem(null);
bug1.Summary = "Lydia Bennet is 15 years old.";
bug1.Status = "New";
bug1.Priority = "3-High";
bug1.Field["BG_SEVERITY"] = "3-High";
bug1.DetectedBy = User.UserName;
bug1.Field["BG_DETECTION_DATE"] = new Date();
bug1.Field["BG_RESPONSIBLE"] = User.UserName;
bug1.Post();
// Create the second bug
const bug2 = await bugF.AddItem(null);
bug2.Summary = "Mr. Bennet hides in library.";
bug2.Status = "New";
bug2.Priority = "3-High";
bug2.Field["BG_SEVERITY"] = "3-High";
bug2.DetectedBy = User.UserName;
bug2.Field["BG_DETECTION_DATE"] = new Date();
bug2.Field["BG_RESPONSIBLE"] = User.UserName;
await bug2.Post();
// Link the new defects
const bgLinkable = bug1; // Casting Bug1 to ILinkable
const bugLinkF = bgLinkable.BugLinkFactory;
// Create a link between Bug1 (source) and Bug2 (target)
const bugLink = bugLinkF.AddItem(bug2);
bugLink.LinkType = "Related";
bugLink.Post();
// Show the link definition
let anObj = bugLink.SourceEntity;
console.log(anObj.Summary); // Lydia Bennet is 15 years old. (Bug1)
anObj = bugLink.TargetEntity;
console.log(anObj.Summary); // Mr. Bennet hides in library. (Bug2)
} catch (err) {
console.error("Error in linkDefects:", err);
}
}
Exemple : Renseigner le cycle des releases cibles dans les enfants
function populateCycle() {
try {
const rFactory = TDConnection.ReqFactory;
// Fetch the requirement item by ID
const requirement = rFactory.Item(1);
// Apply the requirement's target cycle to all descendants
requirement.PopulateTargetCycleToChildren();
} catch (err) {
console.error("Error in populateCycle:", err);
}
}
Exemple : Déplacer des exigences
function moveReqs() {
const rqFactory = TDConnection.ReqFactory;
// Move requirements to a specific position
rqFactory.MoveRequirements("5, 4, 3", "1, 2, 3", 2);
console.assert(false, "After first move:");
// ------------------------------------------------
// Append the Reqs to the end of the existing children
const last = tagTDAPI_POS_ORDER.TDPOSITION_LAST;
const order = `${last},${last},${last}`;
rqFactory.MoveRequirements("3, 5, 4", order, 1);
console.assert(false, "After second move:");
// ------------------------------------------------
// Add the Reqs to the beginning of the existing children
rqFactory.MoveRequirements("3, 4, 5", "1, 1, 1", 2);
console.assert(false, "After third move:");
// ------------------------------------------------
// Place Reqs as specified
rqFactory.MoveRequirements("3, 4, 5", "1, 2, 2", 1);
console.assert(false, "After fourth move:");
}
Exemple : Récupérer des exigences triées
function retrieveOrderedRecords(sinceDate, currentSyncDate) {
try {
const reqFactory = TDConnection.ReqFactory;
if (!reqFactory) {
throw new Error("Request Factory is not initialized.");
}
const filter = reqFactory.Filter;
if (!filter) {
throw new Error("Filter is not initialized.");
}
// Query criteria
filter.Filter["RQ_VTS"] = `> "${sinceDate.toISOString().slice(0, 19).replace('T', ' ')}" AND < "${currentSyncDate.toISOString().slice(0, 19).replace('T', ' ')}"`;
// Sort by path to get parent requirements in list before children
filter.Order["RQ_REQ_PATH"] = 1;
filter.OrderDirection["RQ_REQ_PATH"] = TDOLE_ASCENDING;
// Sort by version timestamp so earlier records output first
filter.Order["RQ_VTS"] = 2;
filter.OrderDirection["RQ_VTS"] = TDOLE_ASCENDING;
// Return the list
const orderedRecords = filter.NewList();
return orderedRecords;
} catch (error) {
console.error("Error in retrieveOrderedRecords:", error);
// Handle error appropriately
}
}
Exemple : Obtenir les tests de couverture non exécutés
function bugProperties(theBug) {
try {
// Print the properties.
console.log("Initial Bug properties");
console.log(theBug.Priority);
console.log(theBug.AssignedTo);
console.log(theBug.DetectedBy);
console.log(theBug.Status);
console.log(theBug.Summary);
// Change the values.
theBug.Priority = "4-Very High";
theBug.AssignedTo = "steves";
theBug.DetectedBy = "alex_alm";
theBug.Status = "Fixed";
theBug.Summary = "Amended: The list of flights is given even when past date set as Departing date";
// Commit to database.
theBug.Post();
// Check the new values.
console.log("Changed Bug properties");
console.log(theBug.Priority);
console.log(theBug.AssignedTo);
console.log(theBug.DetectedBy);
console.log(theBug.Status);
console.log(theBug.Summary);
return "SUCCESS";
} catch (err) {
return "FAILURE";
}
}