diff --git a/.github/scripts/tool_versions.py b/.github/scripts/tool_versions.py index bbfc5bba..8b8ba2f8 100644 --- a/.github/scripts/tool_versions.py +++ b/.github/scripts/tool_versions.py @@ -233,6 +233,40 @@ def renderer(now): # the registry: a path, or a shell variable holding one. LOCAL_ARGUMENT = (".", "/", "~", "$") +# A file name npm installs as a tarball, with or without a path in front. The +# same suffixes npm-package-arg reads as a file rather than a package name. +NPM_TARBALL = re.compile(r"[.](?:tgz|tar[.]gz|tar)$", re.IGNORECASE) + + +def shell_commands(line): + """The simple commands of one shell line, each as its list of words. + + Split where the shell would split, at &&, ||, ;, | and the like, and never + inside quotes: a quoted path holding a ; is one word, as it is to the shell. + A redirection does not end a command. It and the file it names are left + out, with the number of a stream before it, so in + `npm install >log mailparser` the package is still a word of the install. + """ + lexer = shlex.shlex(line, posix=True, punctuation_chars=True) + lexer.whitespace_split = True + commands, words, target_next = [], [], False + for token in lexer: + if target_next: + target_next = False + continue + if token and set(token) <= set("<>&") and token not in ("&", "&&"): + target_next = True + if words and words[-1].isdigit(): + words.pop() + continue + if token and all(c in lexer.punctuation_chars for c in token): + commands.append(words) + words = [] + continue + words.append(token) + commands.append(words) + return [c for c in commands if c] + def npm_pins(texts): """Every registry package an `npm install` in the workflows names, with its pin. @@ -252,24 +286,30 @@ def npm_pins(texts): for name, text in texts.items(): for line in text.splitlines(): command = re.sub(r"^(-\s*)?run:\s*", "", line.strip()) - if command.startswith("#"): + # Only a line where npm install can begin a command is read as + # shell. Any other line, a step name with an apostrophe among + # them, is not shell and must not fail the check. + if not re.search(r"(?:^|[;&|(]\s*)npm\s+install\b", command): continue - for part in re.split(r"&&|\|\||;|\|", command): - if part.split()[:2] != ["npm", "install"]: + try: + commands = shell_commands(command) + except ValueError as exc: + raise RuntimeError(f"{name} runs an npm install this cannot read ({exc}): {line.strip()}") from exc + for words in commands: + if words[:2] != ["npm", "install"]: continue - try: - words = shlex.split(part)[2:] - except ValueError as exc: - raise RuntimeError(f"{name} runs an npm install this cannot read ({exc}): {line.strip()}") from exc value_next = False - for word in words: + for word in words[2:]: if value_next: value_next = False continue if word in NPM_VALUE_OPTIONS: value_next = True continue - if word.startswith("-") or word.startswith(LOCAL_ARGUMENT): + # A name starting with @ is a scoped package of the + # registry whatever it ends with, as npm-package-arg reads it. + tarball = NPM_TARBALL.search(word) and not word.startswith("@") + if word.startswith("-") or word.startswith(LOCAL_ARGUMENT) or tarball: continue m = re.fullmatch(r"(@?[\w./-]+)@(\d[\w.+-]*)", word) if not m: diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index 90831ccf..fcc90545 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -37,7 +37,7 @@ jobs: # checked against the SHA256SUMS the page was rendered with before it may go # out, so the sums a visitor reads are the sums of the bytes they download. # A job of its own, with nothing but read access, because it builds and runs - # repository code and the job that publishes holds pages: write. + # repository code and the job that deploys holds pages: write. samples: if: >- github.event_name == 'workflow_dispatch' || @@ -84,22 +84,24 @@ jobs: publish: needs: samples + # Read access only. It uploads the site, and the deploy job after it is the + # one that publishes. configure-pages only reads the Pages settings here. permissions: contents: read - pages: write - id-token: write + pages: read # A dispatch is a person asking on purpose. Everything else has to be CI # saying the tree is good, ON THIS REPOSITORY, for a push. # # The last two conditions were added on 2026-08-27, the day this project # started taking pull requests, and they close a hole that opened with it. # This job runs on workflow_run, which fires in the base repository with the - # base repository's permissions - and it holds pages: write. CI runs on + # base repository's permissions - and the deploy job after it, which runs + # only when this one does, holds pages: write. CI runs on # pull_request, and the branches filter above matches the branch NAME of the # run that triggered it, which for a fork is a name the fork chose. A fork # whose branch is called main, opening a pull request that passes CI, would - # otherwise reach this job, and this job publishes web/public to the project - # website. + # otherwise reach this job, and the two jobs publish web/public to the + # project website. # # Nothing here executes repository code, so the exposure was defacement # rather than anything reaching a secret. That is still not a thing to leave diff --git a/CHANGELOG.md b/CHANGELOG.md index edc9db00..33f7b413 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,17 @@ because it turns other people's test suites red. and the outcome to expect, in every language of the site. - **A page about the tools on the website.** Checking an archive for zip slip and zip bombs before unpacking it, and checking or writing SHA-256 checksums. +- **Documentation on the website, in English.** Install, getting started, + every command with every flag and its default, every key of a recipe, every + field of the manifest, every setting of every format, the packages for + pytest and Node, and the desktop window screen by screen. The lists come + from the program when the site is built, so they say what the version you + download does. The documentation page in the other languages leads to them, + with a line about each page in your language. +- **Recipes to download.** Ready recipes for an image upload, a document + upload, a spreadsheet import, archives, email, video and sound, a CI smoke + test and ten thousand files, and every preset as a recipe. Each writes into a + folder of its own name, so several can run one after another. ### Changed diff --git a/SECURITY.md b/SECURITY.md index 0e0ca073..31af24bd 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -104,10 +104,11 @@ could post a summary comment on a pull request, which would need `pull-requests: write` - that scope is deliberately not granted, because a failing check already says what the comment would. -Two workflows hold more. The one that publishes the website has `pages: write` -and `id-token: write`. It has a single job, and it runs only for a push to this -repository - a condition added on 2026-08-27 and held by a guard, because the event -it triggers on fires with this repository's permissions. The weekly vulnerability +Two workflows hold more. In the one that publishes the website, only the last +job, which deploys what the jobs before it built and uploaded, has `pages: write` +and `id-token: write`. Those jobs have read access only. The workflow runs only for +a push to this repository - a condition added on 2026-08-27 and held by a guard, +because the event it triggers on fires with this repository's permissions. The weekly vulnerability scan has `security-events: write`, on its one job, to put its results in the Security tab. It runs on a schedule or by hand, never for a pull request. diff --git a/internal/guard/commanddeclaration_test.go b/internal/guard/commanddeclaration_test.go index 55a4f9ec..74cd6219 100644 --- a/internal/guard/commanddeclaration_test.go +++ b/internal/guard/commanddeclaration_test.go @@ -28,26 +28,6 @@ import ( // generate, so they get guards - and both are asked with a rule rather than a // list of exceptions, because a list of exceptions is a guard with a hole. -// commandsTheToolPrints is the command names out of tfg --help, which is the -// text the page is a copy of. -// -// Asked of the help rather than of the router beside it on purpose: the help -// is what a visitor compares the page against, so agreeing with anything else -// would prove the wrong thing. -func commandsTheToolPrints(t *testing.T) []string { - t.Helper() - var out, errOut bytes.Buffer - if code := cli.Run(context.Background(), []string{"--help"}, &out, &errOut); code != cli.ExitOK { - t.Fatalf("tfg --help ended with %d rather than %d, so there is no list to compare against", - code, cli.ExitOK) - } - names, err := commandNamesIn(out.String()) - if err != nil { - t.Fatalf("reading the command block out of tfg --help: %v", err) - } - return names -} - // commandNamesIn takes the names out of the Commands: block of a help text. // // Split on two spaces rather than on the first one, because "recipe fmt" is a diff --git a/internal/guard/mutationcoverage_test.go b/internal/guard/mutationcoverage_test.go index a3e3602d..cc46876f 100644 --- a/internal/guard/mutationcoverage_test.go +++ b/internal/guard/mutationcoverage_test.go @@ -281,8 +281,18 @@ var provenByProbe = map[string]string{ "red on the message in npm.yml that stopped the weekly runs of 2026-11-16 and 2026-11-23.", "TestOneFailingToolVersionCheckLeavesTheOthersRunning": "its canary is the planted failure of the first check. " + "Broken by hand on 2026-11-24 by ending the run at the first failure again: red, the pins after it unprinted.", - "TestTheSiteIsDeployedInAJobAfterTheUploadWithMoreThanOneTry": "a canary of its own - one job that uploads and " + - "deploys once has to give two problems. Broken by hand on 2026-11-24 by the pages.yml of main that day: red three times.", + "TestTheSiteIsDeployedInAJobAfterTheUploadWithMoreThanOneTry": "two canaries of its own, the old layout and a retry " + + "reading the conclusion. Broken by hand on 2026-11-24 by main's pages.yml and by that retry: red both times.", + "TestTheCommandReferenceIsReadFromTheHelp": "a canary help of every shape it reads, and one it cannot. Broken by hand " + + "on 2026-11-24 by reading flags only after three spaces: red.", + "TestTheReferenceDescribesEveryKeyFieldAndRecipe": "a canary of an item without a sentence and a sentence without an " + + "item. Broken by hand on 2026-11-24 by taking files[].send_as out of the English reference: red.", + "TestEveryRecipeOfTheGalleryIsValidAndWritesToItsOwnFolder": "a canary recipe writing into another folder. Broken " + + "by hand on 2026-11-24 by pointing ci-smoke.yaml at ./out: red.", + "TestEveryLanguageLeadsToTheEnglishDocumentation": "the canary of the comparison it shares, and English pages must " + + "exist. Broken by hand on 2026-11-24 by taking one guide out of the Polish language file: red.", + "TestEveryHeldBackAdvisoryHasAnEndDateAndAReason": "a canary of its own - an entry without a date and one without " + + "a reason have to give two problems. Broken by hand on 2026-11-24 by taking one ignoreUntil out of the real file: red.", "TestAReleaseCandidateIsSentNowhereButGitHub": "a canary of its own - a which step that sends whatever it is " + "given has to fail the same cases. Broken by hand on 2026-11-23 by the npm.yml, pypi.yml and docker.yml of " + "main before the change: red six times, each of the three sending a published release candidate and taking " + diff --git a/internal/guard/osvexceptions_test.go b/internal/guard/osvexceptions_test.go new file mode 100644 index 00000000..313268f2 --- /dev/null +++ b/internal/guard/osvexceptions_test.go @@ -0,0 +1,164 @@ +package guard + +import ( + "fmt" + "path/filepath" + "regexp" + "strconv" + "strings" + "testing" + "time" +) + +// osvKeyValue is one key = value line of a TOML table. +var osvKeyValue = regexp.MustCompile(`^([A-Za-z]+)\s*=\s*(.*)$`) + +// osvTableHeader is the header of one held back advisory. TOML allows spaces +// inside the brackets and a comment after them. +var osvTableHeader = regexp.MustCompile(`(?m)^[ \t]*\[\[[ \t]*IgnoredVulns[ \t]*\]\][ \t]*(?:#.*)?$`) + +// osvExceptionProblems is what is wrong with the held back advisories of an +// OSV-Scanner configuration: an entry without an id, without a date it stops +// working on, or without a reason. +// +// Read line by line rather than with a TOML parser, which this module only has +// as a dependency of a dependency. The file is flat: one [[IgnoredVulns]] +// table per advisory, with one key per line. An entry written any other way, +// as an inline table, is refused rather than skipped, so it cannot slip past. +func osvExceptionProblems(body string) []string { + var problems []string + heads := osvTableHeader.FindAllStringIndex(body, -1) + if mentions := osvMentions(body); mentions != len(heads) { + problems = append(problems, fmt.Sprintf("IgnoredVulns appears on %d line(s) and %d of them are a table header "+ + "this reads, so an entry is written in a layout this guard does not check", mentions, len(heads))) + } + for i, h := range heads { + end := len(body) + if i+1 < len(heads) { + end = heads[i+1][0] + } + problems = append(problems, osvEntryProblems(i+1, osvKeys(body[h[1]:end]))...) + } + return problems +} + +// osvMentions is how many lines that are not a comment name IgnoredVulns. +func osvMentions(body string) int { + n := 0 + for _, line := range strings.Split(body, "\n") { + if !strings.HasPrefix(strings.TrimSpace(line), "#") && strings.Contains(line, "IgnoredVulns") { + n++ + } + } + return n +} + +// osvKeys is the keys of one table, up to the next header of any table. +func osvKeys(block string) map[string]string { + keys := map[string]string{} + for _, line := range strings.Split(block, "\n") { + line = strings.TrimSpace(line) + if strings.HasPrefix(line, "[") { + break + } + if m := osvKeyValue.FindStringSubmatch(line); m != nil { + keys[m[1]] = strings.TrimSpace(m[2]) + } + } + return keys +} + +// osvEntryProblems is what is wrong with entry n. +func osvEntryProblems(n int, keys map[string]string) []string { + var problems []string + id, _ := tomlString(keys["id"]) + name := strconv.Quote(id) + if id == "" { + name = "entry " + strconv.Itoa(n) + problems = append(problems, name+" names no advisory") + } + until := keys["ignoreUntil"] + if len(until) < 10 { + problems = append(problems, name+" has no ignoreUntil, so it holds the advisory back for good") + } else if _, err := time.Parse(time.DateOnly, until[:10]); err != nil { + problems = append(problems, name+" has an ignoreUntil that is not a date: "+until) + } + if reason, ok := tomlString(keys["reason"]); !ok || strings.TrimSpace(reason) == "" { + problems = append(problems, name+" gives no reason, and the scan prints the reason beside every advisory it holds back") + } + return problems +} + +// tomlString is the text of a TOML string value, with what follows it, a +// comment among them, left out. False when the value is not a string. +func tomlString(v string) (string, bool) { + v = strings.TrimSpace(v) + if strings.HasPrefix(v, "'") { + end := strings.Index(v[1:], "'") + return v[1 : 1+max(end, 0)], end >= 0 + } + if !strings.HasPrefix(v, `"`) { + return "", false + } + var b strings.Builder + for i := 1; i < len(v); i++ { + switch c := v[i]; { + case c == '\\' && i+1 < len(v): + b.WriteByte(v[i+1]) + i++ + case c == '"': + return b.String(), true + default: + b.WriteByte(c) + } + } + return "", false +} + +// Every advisory the OSV scan holds back has a date it stops working on and a +// reason. +// +// The date is what brings an advisory back: when it passes, the weekly scan +// goes red again and the entry has to be read again. An entry without one holds +// the advisory back for good and nothing says so. The header of the file +// promises a date for every entry, and nothing else checks that promise. +// +// Its own canary: entries without a date, with an empty reason, with spaces in +// the header and with a comment after an empty reason have to be reported, an +// entry with a # inside its reason must not be, and an inline table is refused. +func TestEveryHeldBackAdvisoryHasAnEndDateAndAReason(t *testing.T) { + canary := `[[IgnoredVulns]] +id = "GHSA-aaaa-aaaa-aaaa" +reason = "held back" + +[[IgnoredVulns]] +id = "GHSA-bbbb-bbbb-bbbb" +ignoreUntil = 2026-12-14 +reason = "" + +[[ IgnoredVulns ]] +id = "GHSA-cccc-cccc-cccc" +reason = "held back" + +[[IgnoredVulns]] +id = "GHSA-dddd-dddd-dddd" +ignoreUntil = 2026-12-14 +reason = "" # explain later + +[[IgnoredVulns]] +id = "GHSA-eeee-eeee-eeee" +ignoreUntil = 2026-12-14 +reason = "held back # until the fix ships" +` + if got := osvExceptionProblems(canary); len(got) != 4 { + t.Fatalf("the canary, four broken entries and one whole one, gave %d problem(s) and has four: %v", len(got), got) + } + if got := osvExceptionProblems("IgnoredVulns = [{ id = \"GHSA-ffff-ffff-ffff\" }]\n"); len(got) != 1 { + t.Fatalf("an entry written as an inline table was not refused: %v", got) + } + + body := readRepoFile(t, filepath.Join(".github", "osv-scanner.toml")) + for _, p := range osvExceptionProblems(body) { + t.Error(p) + } +} diff --git a/internal/guard/pagesdeploy_test.go b/internal/guard/pagesdeploy_test.go index eb84ea92..9b418de7 100644 --- a/internal/guard/pagesdeploy_test.go +++ b/internal/guard/pagesdeploy_test.go @@ -1,8 +1,6 @@ package guard import ( - "os" - "path/filepath" "strings" "testing" @@ -12,22 +10,27 @@ import ( // pagesStep is the part of a workflow step this guard reads. type pagesStep struct { ID string `yaml:"id"` + If string `yaml:"if"` Uses string `yaml:"uses"` ContinueOnError bool `yaml:"continue-on-error"` } // pagesJob is the part of a workflow job this guard reads. type pagesJob struct { - Needs any `yaml:"needs"` - Steps []pagesStep `yaml:"steps"` + Needs any `yaml:"needs"` + Permissions any `yaml:"permissions"` + Steps []pagesStep `yaml:"steps"` } // pagesDeployProblems is what is wrong with how a workflow uploads and deploys // the site: nothing when the deployment runs in a job of its own, after the -// job that uploads, and asks for the artifact more than once. +// job that uploads, and asks for the artifact more than once, each try after +// the first only when the one before it failed, and the job that only uploads +// holds no write access to Pages. func pagesDeployProblems(body []byte) []string { var workflow struct { - Jobs map[string]pagesJob `yaml:"jobs"` + Permissions any `yaml:"permissions"` + Jobs map[string]pagesJob `yaml:"jobs"` } if err := yaml.Unmarshal(body, &workflow); err != nil { return []string{"the workflow does not parse: " + err.Error()} @@ -47,6 +50,17 @@ func pagesDeployProblems(body []byte) []string { return []string{"no job uploads the site or none deploys it, so there is nothing here to check"} } var problems []string + for name := range uploads { + // A job without permissions of its own has the workflow's. + held := workflow.Jobs[name].Permissions + if held == nil { + held = workflow.Permissions + } + if _, deploys := deploys[name]; !deploys && writesPages(held) { + problems = append(problems, "the job "+name+" only uploads the site and still holds pages: write or "+ + "id-token: write, which only the deploy job needs") + } + } for name, steps := range deploys { if uploads[name] { problems = append(problems, "the job "+name+" uploads the site and deploys it, and in one job the "+ @@ -77,6 +91,9 @@ func pagesDeployProblems(body []byte) []string { problems = append(problems, "try "+s.ID+" of "+name+" ends the job when it fails, so the tries after it never run") } } + for i := 1; i < len(steps); i++ { + problems = append(problems, retryConditionProblems(name, steps[:i], steps[i])...) + } if steps[len(steps)-1].ContinueOnError { problems = append(problems, "the last try of "+name+" may fail without failing the job, so a site that never went out would look published") } @@ -84,6 +101,65 @@ func pagesDeployProblems(body []byte) []string { return problems } +// writesPages tells whether a job's permissions let it publish to Pages or +// ask for an OIDC token. +func writesPages(permissions any) bool { + switch p := permissions.(type) { + case string: + return p == "write-all" + case map[string]any: + return p["pages"] == "write" || p["id-token"] == "write" + } + return false +} + +// retryConditionProblems is what is wrong with the condition of a try that +// should run exactly when every try before it failed. +// +// The whole condition is compared, not a part of it: one that also says +// "&& false" never runs, and one that also says "|| true" runs after a try +// that worked. It has to ask for the outcome. A step with continue-on-error +// that failed has the conclusion success, so a try that waited for the +// conclusion failure of the one before would never run, and the job would end +// green with nothing deployed. +func retryConditionProblems(job string, before []pagesStep, try pagesStep) []string { + asks := make([]string, len(before)) + for i, b := range before { + asks[i] = "steps." + b.ID + ".outcome == 'failure'" + } + want := strings.Join(asks, " && ") + said := strings.Join(strings.Fields(strings.TrimSuffix(strings.TrimPrefix(strings.TrimSpace(try.If), "${{"), "}}")), " ") + var problems []string + if said != want { + problems = append(problems, "try "+try.ID+" of "+job+" runs on "+said+" rather than exactly "+want+ + ", so it runs when it should not or never runs at all") + } + if strings.Contains(try.If, ".conclusion") { + problems = append(problems, "try "+try.ID+" of "+job+" reads a conclusion, and a failed step with "+ + "continue-on-error concludes as success, so this try never runs") + } + return problems +} + +// pagesCanary is a workflow that uploads in one job and deploys twice in the +// next, with the permissions and the condition of the second try given. +func pagesCanary(workflowPermissions, uploadPermissions, retryIf string) []byte { + return []byte(workflowPermissions + `jobs: + publish: +` + uploadPermissions + ` steps: + - uses: actions/upload-pages-artifact@abc + deploy: + needs: publish + steps: + - id: first + uses: actions/deploy-pages@abc + continue-on-error: true + - id: second + if: ` + retryIf + ` + uses: actions/deploy-pages@abc +`) +} + // The site is deployed in a job of its own, after the upload, with more than // one try. // @@ -93,8 +169,10 @@ func pagesDeployProblems(body []byte) []string { // (actions/deploy-pages#451). Re-running the failed job cannot recover it, // because the re-run uploads a second github-pages artifact. // -// Its own canary: the job as it stood on main that day, uploading and -// deploying once in the same job, has to be reported. +// Its canaries: the job as it stood on main that day, uploading and deploying +// once in the same job, retries whose condition is not exactly "every try +// before me failed", and an upload job holding pages: write, its own or the +// workflow's. Every problem has to be reported, and a correct layout none. func TestTheSiteIsDeployedInAJobAfterTheUploadWithMoreThanOneTry(t *testing.T) { canary := []byte(`jobs: publish: @@ -108,12 +186,29 @@ func TestTheSiteIsDeployedInAJobAfterTheUploadWithMoreThanOneTry(t *testing.T) { t.Fatalf("the canary, one job that uploads and deploys once, gave %d problem(s) and has two: %v", len(got), got) } - path := filepath.Join(repoRoot(t), ".github", "workflows", "pages.yml") - body, err := os.ReadFile(path) - if err != nil { - t.Skipf("the publishing workflow is not here: %v", err) + // The other canaries: retries that read the conclusion or say more than + // they should, and an upload job that holds the write access only the + // deploy job needs, by its own permissions or by the workflow's. A correct + // layout and an empty override of the workflow's permissions pass. + const retry, write, wide = "steps.first.outcome == 'failure'", " permissions:\n pages: write\n id-token: write\n", "permissions:\n pages: write\n" + for _, c := range []struct { + why string + workflow, upload, at string + problems int + }{ + {"a correct layout", "", "", retry, 0}, + {"a retry reading the conclusion after an upload job with pages: write", "", write, "steps.first.conclusion == 'failure'", 3}, + {"a retry that never runs", "", "", retry + " && false", 1}, + {"a retry that runs after a try that worked", "", "", retry + " || true", 1}, + {"an upload job inheriting pages: write", wide, "", retry, 1}, + {"an upload job overriding the workflow with nothing", wide, " permissions: {}\n", retry, 0}, + } { + if got := pagesDeployProblems(pagesCanary(c.workflow, c.upload, c.at)); len(got) != c.problems { + t.Fatalf("the canary of %s gave %d problem(s) and has %d: %v", c.why, len(got), c.problems, got) + } } - for _, p := range pagesDeployProblems(body) { + + for _, p := range pagesDeployProblems([]byte(workflowText(t, "pages.yml"))) { t.Error(p) } } diff --git a/internal/guard/publishcondition_test.go b/internal/guard/publishcondition_test.go index 367279a1..b0cc87a5 100644 --- a/internal/guard/publishcondition_test.go +++ b/internal/guard/publishcondition_test.go @@ -9,13 +9,14 @@ import ( // Publishing the website happens for a push to this repository, and nothing else. // -// The job that deploys web/public triggers on workflow_run. That event fires in -// the BASE repository, with the base repository's permissions, and this job -// holds pages: write. CI runs on pull_request, and the branches filter on +// The job that uploads web/public triggers on workflow_run, and the deploy job +// that publishes it runs only after that one. The event fires in the BASE +// repository, with the base repository's permissions, and the deploy job holds +// pages: write. CI runs on pull_request, and the branches filter on // workflow_run matches the branch NAME of the run that triggered it - which for // a pull request from a fork is a name the fork chose. A fork whose branch was // called main, opening a pull request that passed CI, would otherwise satisfy -// every condition this job had before 2026-08-27. +// every condition the upload job had before 2026-08-27. // // Nothing in the job executes repository code. It checks three files exist and // uploads a directory, so what was reachable was the content of the published @@ -58,7 +59,7 @@ func TestTheSiteIsPublishedOnlyForAPushToThisRepository(t *testing.T) { if !strings.Contains(text, want.needle) { t.Errorf("the publish job does not ask for %q.\n"+ "That condition is there because %s.\n"+ - "This job runs with the base repository's permissions and holds pages: write.", + "It runs with the base repository's permissions, and the deploy job after it holds pages: write.", want.needle, want.why) } } diff --git a/internal/guard/site_test.go b/internal/guard/site_test.go index 286600cb..918449d9 100644 --- a/internal/guard/site_test.go +++ b/internal/guard/site_test.go @@ -19,6 +19,7 @@ import ( "github.com/donislawdev/TestingFilesGenerator/internal/damage" "github.com/donislawdev/TestingFilesGenerator/internal/format" _ "github.com/donislawdev/TestingFilesGenerator/internal/format/all" + "github.com/donislawdev/TestingFilesGenerator/internal/recipe" "github.com/donislawdev/TestingFilesGenerator/internal/site" "github.com/donislawdev/TestingFilesGenerator/internal/version" ) @@ -118,6 +119,8 @@ func factsFromTheProgram(t *testing.T) site.Facts { }) } + presets := presetFactsFromTheProgram(t) + docs, recipes := commandDocsAndRecipes(t, presets) return site.Facts{ Version: version.Version, Released: releasedVersionOfThisBuild(t), @@ -126,8 +129,9 @@ func factsFromTheProgram(t *testing.T) site.Facts { Damages: damagesTheProgramHas(), Samples: samplesFromTheRecipe(t), Tools: toolsTheProgramHas(), - Presets: presetFactsFromTheProgram(t), - Commands: commandsTheToolPrints(t), + Presets: presets, + Docs: site.DocsFacts{Commands: docs, RecipeKeys: recipe.Keys(), Outcomes: recipe.Outcomes(), + Reasons: recipe.Reasons(), ManifestFields: manifestFieldsOf(), Recipes: recipes}, Downloads: declaredDownloads(), // Fixed on purpose. See the comment on the field. Year: 2026, @@ -203,6 +207,13 @@ func siteUnderTest(t *testing.T) site.Site { Extra: map[string]string{ "assets/window.png": filepath.Join(repoRoot(t), ".github", "window.png"), "assets/icon.png": filepath.Join(repoRoot(t), "internal", "gui", "icon", "chickpea.png"), + // The screens of the desktop app page are the references the + // window guards render with the real toolkit, so a change to a + // screen is a change to the page and turns the site guard red. + "assets/window/single-batch.png": filepath.Join(repoRoot(t), "internal", "guard", "testdata", "screens", "generate.png"), + "assets/window/presets.png": filepath.Join(repoRoot(t), "internal", "guard", "testdata", "screens", "preset.png"), + "assets/window/several-batches.png": filepath.Join(repoRoot(t), "internal", "guard", "testdata", "screens", "recipe.png"), + "assets/window/tools.png": filepath.Join(repoRoot(t), "internal", "guard", "testdata", "screens", "tools-result.png"), // Published beside the files it makes, so the command on the page // has its recipe one click away. site.SamplesDir + "/samples.yaml": filepath.Join(repoRoot(t), filepath.FromSlash(sampleFilesRecipe)), @@ -409,7 +420,7 @@ func TestEveryLanguageDescribesEverythingTheProgramCanProduce(t *testing.T) { // command dropped from the program leaves its summary behind in both // language files, and the page would then be a list of what the tool // used to have - the same defect as a missing one, read backwards. - for _, name := range facts.Commands { + for _, name := range facts.Docs.CommandNames() { if _, ok := lang.Commands[name]; !ok { t.Errorf("the command %q has no summary in %s, so the page would list it blank", name, lang.Code) } @@ -435,7 +446,7 @@ func TestEveryLanguageDescribesEverythingTheProgramCanProduce(t *testing.T) { } } for name := range lang.Commands { - if !slices.Contains(facts.Commands, name) { + if !slices.Contains(facts.Docs.CommandNames(), name) { t.Errorf("%s describes a command %q that tfg --help does not print", lang.Code, name) } } @@ -482,13 +493,23 @@ func TestEveryPageExistsInEveryLanguage(t *testing.T) { t.Skip("one language, so nothing can be missing from another") } keys := map[string]int{} + // A page marked untranslated exists in the root language alone, on purpose + // (internal/site/docs.go), and has to exist nowhere else - the render + // refuses that as well, and this says it without rendering. + untranslated := map[string]bool{} for _, l := range langs { for _, p := range l.Pages { keys[p.Key]++ + if p.Untranslated && l.Dir == "" { + untranslated[p.Key] = true + } } } for key, count := range keys { - if count != len(langs) { + switch { + case untranslated[key] && count != 1: + t.Errorf("the page %q is marked untranslated and exists in %d languages", key, count) + case !untranslated[key] && count != len(langs): t.Errorf("the page %q exists in %d of %d languages, so its language switch leads nowhere", key, count, len(langs)) } } diff --git a/internal/guard/sitedocs_test.go b/internal/guard/sitedocs_test.go new file mode 100644 index 00000000..c5984fdd --- /dev/null +++ b/internal/guard/sitedocs_test.go @@ -0,0 +1,497 @@ +package guard + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "maps" + "os" + "path/filepath" + "reflect" + "regexp" + "slices" + "sort" + "strconv" + "strings" + "sync" + "testing" + + "github.com/goccy/go-yaml" + + "github.com/donislawdev/TestingFilesGenerator/internal/cli" + "github.com/donislawdev/TestingFilesGenerator/internal/manifest" + "github.com/donislawdev/TestingFilesGenerator/internal/recipe" + "github.com/donislawdev/TestingFilesGenerator/internal/site" +) + +// The pages of the documentation state what the program says about itself: +// the help of every command, the keys of a recipe, the fields of a manifest and +// the recipes to download. The functions here read those out of the program, +// and the guards below hold the English sentences beside them to it in both +// directions, so a flag, a key or a field added without a word about it stops +// the render, and a sentence about one that is gone turns a guard red +// (docs/DOCS-SITE-2026-11-24.md). + +// recipeGalleryDir holds the recipes the gallery offers for download. +const recipeGalleryDir = "web/recipes" + +// docsAnswers are read once per process, since several site guards render the +// whole site and the answers cannot change between them. +var docsAnswers struct { + once sync.Once + docs []site.CommandDoc + recipes []site.Recipe + err error +} + +// commandDocsAndRecipes asks the program for the help of every command and +// runs every recipe of the gallery dry. +func commandDocsAndRecipes(t *testing.T, presets []site.PresetFacts) ([]site.CommandDoc, []site.Recipe) { + t.Helper() + root := repoRoot(t) + docsAnswers.once.Do(func() { + docsAnswers.docs, docsAnswers.err = commandDocsOfTheProgram() + if docsAnswers.err == nil { + docsAnswers.recipes, docsAnswers.err = galleryRecipesOf(filepath.Join(root, filepath.FromSlash(recipeGalleryDir)), presets) + } + }) + if docsAnswers.err != nil { + t.Fatal(docsAnswers.err) + } + return docsAnswers.docs, docsAnswers.recipes +} + +// commandDocsOfTheProgram is every command tfg --help lists, in its order and +// read out of its text, each as its own --help describes it. +func commandDocsOfTheProgram() ([]site.CommandDoc, error) { + top, err := runQuietly("--help") + if err != nil { + return nil, err + } + names, err := commandNamesIn(string(top)) + if err != nil { + return nil, fmt.Errorf("reading the command block out of tfg --help: %w", err) + } + summaries := map[string]string{} + for _, c := range cli.Commands() { + summaries[c.Name] = c.Summary + } + out := make([]site.CommandDoc, 0, len(names)) + for _, name := range names { + var stdout, stderr bytes.Buffer + args := append(strings.Fields(name), "--help") + if code := cli.Run(context.Background(), args, &stdout, &stderr); code != cli.ExitOK { + return nil, fmt.Errorf("tfg %s ended with %d: %s", strings.Join(args, " "), code, stderr.String()) + } + doc, err := parseCommandHelp(name, summaries[name], stdout.String()) + if err != nil { + return nil, err + } + out = append(out, doc) + } + return out, nil +} + +// flagDefault is the end flag.PrintDefaults gives a flag whose default is not +// its zero value. +var flagDefault = regexp.MustCompile(` \(default (.*)\)$`) + +// parseCommandHelp reads one --help into its parts. +// +// The help is the text a reader compares the page against, so it is read +// rather than the flag sets behind it. A command whose --help prints no help +// of its own, as version prints the version, gets the summary of tfg --help +// and nothing else. A help that has a Flags block and gives no flag, or a flag +// without words, is an error: a change in what flag.PrintDefaults writes would +// otherwise leave the page without its tables and every check green. +func parseCommandHelp(name, summary, help string) (site.CommandDoc, error) { + doc := site.CommandDoc{Name: name, Summary: sentence(summary)} + head := "tfg " + name + " - " + if !strings.HasPrefix(help, head) { + return doc, nil + } + first, rest, _ := strings.Cut(help, "\n") + doc.Summary = sentence(strings.TrimPrefix(first, head)) + usageSeen, flagsSeen := false, false + for _, block := range strings.Split(strings.ReplaceAll(rest, "\r\n", "\n"), "\n\n") { + block = strings.Trim(block, "\n") + switch { + case block == "": + case strings.HasPrefix(block, "Usage:\n"): + usageSeen = true + for _, line := range strings.Split(strings.TrimPrefix(block, "Usage:\n"), "\n") { + doc.Usage = append(doc.Usage, strings.TrimPrefix(line, " ")) + } + case strings.HasPrefix(block, "Flags:\n"): + flagsSeen = true + flags, err := parseFlags(strings.TrimPrefix(block, "Flags:\n")) + if err != nil { + return doc, fmt.Errorf("tfg %s --help: %w", name, err) + } + doc.Flags = append(doc.Flags, flags...) + case usageSeen: + doc.Notes = append(doc.Notes, strings.Join(strings.Fields(block), " ")) + default: + doc.About = append(doc.About, strings.Join(strings.Fields(block), " ")) + } + } + if !usageSeen { + return doc, fmt.Errorf("tfg %s --help has no Usage block, so its section would not say how to run it", name) + } + if flagsSeen && len(doc.Flags) == 0 { + return doc, fmt.Errorf("tfg %s --help has a Flags block and no flag was read out of it", name) + } + return doc, nil +} + +// parseFlags reads the block flag.PrintDefaults writes: " -name type" and the +// words under it after a tab, or " -x" and the words on the same line after a +// tab for a short name. +func parseFlags(block string) ([]site.FlagDoc, error) { + var out []site.FlagDoc + for _, line := range strings.Split(block, "\n") { + switch { + case strings.HasPrefix(line, " -"): + head, words, short := strings.Cut(strings.TrimPrefix(line, " -"), "\t") + name, takes, _ := strings.Cut(head, " ") + f := site.FlagDoc{Name: name, Takes: strings.TrimSpace(takes)} + if short { + f.Text = strings.TrimSpace(words) + } + out = append(out, f) + case strings.HasPrefix(line, " \t") && len(out) > 0: + last := &out[len(out)-1] + last.Text = strings.TrimSpace(last.Text + " " + strings.TrimPrefix(line, " \t")) + default: + return nil, fmt.Errorf("a line of the Flags block is in no shape this reads: %q", line) + } + } + for i := range out { + if m := flagDefault.FindStringSubmatch(out[i].Text); m != nil { + out[i].Text = strings.TrimSuffix(out[i].Text, m[0]) + out[i].Default = m[1] + if unquoted, err := strconv.Unquote(m[1]); err == nil { + out[i].Default = unquoted + } + } + if out[i].Name == "" || out[i].Text == "" { + return nil, fmt.Errorf("the flag %q has no name or no words", out[i].Name) + } + } + return out, nil +} + +// sentence starts a line of the help with a capital and ends it with a stop, +// as a sentence on a page. +func sentence(s string) string { + s = strings.TrimSuffix(strings.TrimSpace(s), ".") + if s == "" { + return s + } + return strings.ToUpper(s[:1]) + s[1:] + "." +} + +// manifestFieldsOf is every field a manifest can carry, by dotted path, in the +// order the structures declare them. An element of a list is written as [] and +// a value of a map keyed by the user's words as *. +func manifestFieldsOf() []string { + var out []string + var walk func(t reflect.Type, prefix string) + walk = func(t reflect.Type, prefix string) { + for t.Kind() == reflect.Pointer { + t = t.Elem() + } + switch t.Kind() { + case reflect.Slice: + walk(t.Elem(), prefix+"[]") + return + case reflect.Map: + walk(t.Elem(), prefix+".*") + return + case reflect.Struct: + default: + return + } + for i := 0; i < t.NumField(); i++ { + f := t.Field(i) + if f.Anonymous { + walk(f.Type, prefix) + continue + } + name, _, _ := strings.Cut(f.Tag.Get("json"), ",") + if !f.IsExported() || name == "" || name == "-" { + continue + } + path := name + if prefix != "" { + path = prefix + "." + name + } + out = append(out, path) + walk(f.Type, path) + } + } + walk(reflect.TypeOf(manifest.Manifest{}), "") + return out +} + +// galleryRecipesOf is every recipe of the gallery, by file name, and every +// preset as the recipe tfg preset eject prints, each with what a dry run +// counts. +func galleryRecipesOf(dir string, presets []site.PresetFacts) ([]site.Recipe, error) { + names, err := filepath.Glob(filepath.Join(dir, "*.yaml")) + if err != nil { + return nil, err + } + sort.Strings(names) + var out []site.Recipe + for _, file := range names { + body, err := os.ReadFile(file) + if err != nil { + return nil, err + } + r := site.Recipe{ID: strings.TrimSuffix(filepath.Base(file), ".yaml"), Body: body} + if r.Files, r.Bytes, r.Formats, err = dryRunOf(file); err != nil { + return nil, err + } + out = append(out, r) + } + for _, p := range presets { + body, err := runQuietly("preset", "eject", p.ID) + if err != nil { + return nil, err + } + out = append(out, site.Recipe{ID: p.ID, Preset: true, Body: body, + Files: p.Budget.Files, Bytes: p.Budget.Bytes, Formats: p.Budget.Formats}) + } + return out, nil +} + +// dryRunOf is what a dry run of one recipe counts: files, bytes and formats. +func dryRunOf(file string) (int, int64, []string, error) { + dir, err := os.MkdirTemp("", "tfg-gallery-") + if err != nil { + return 0, 0, nil, err + } + defer os.RemoveAll(dir) + printed, err := runQuietly("generate", file, "--dry-run", "--json", "--out", dir) + if err != nil { + return 0, 0, nil, err + } + // The bytes are added up from the files. The summary of a dry run counts + // what was written, which is nothing. + var m struct { + Summary struct { + FileCount int `json:"file_count"` + ByFormat map[string]int `json:"by_format"` + } `json:"summary"` + Files []struct { + Bytes int64 `json:"bytes"` + } `json:"files"` + } + if err := json.Unmarshal(printed, &m); err != nil { + return 0, 0, nil, fmt.Errorf("reading the dry run of %s: %w", filepath.Base(file), err) + } + var total int64 + for _, f := range m.Files { + total += f.Bytes + } + formats := make([]string, 0, len(m.Summary.ByFormat)) + for f := range m.Summary.ByFormat { + formats = append(formats, f) + } + sort.Strings(formats) + return m.Summary.FileCount, total, formats, nil +} + +// describedBothWays is what is wrong between the items the program has and +// the sentences written about them: an item without one, and a sentence about +// an item the program does not have. +func describedBothWays[V any](what string, items []string, said map[string]V) []string { + var out []string + for _, item := range items { + if _, ok := said[item]; !ok { + out = append(out, fmt.Sprintf("the %s %q has no sentence", what, item)) + } + } + for item := range said { + if !slices.Contains(items, item) { + out = append(out, fmt.Sprintf("there is a sentence about the %s %q, which the program does not have", what, item)) + } + } + sort.Strings(out) + return out +} + +// The command reference is read out of each command's own --help. +// +// Its canary: a help in every shape the reader knows - a flag with a type and +// a default, a short flag on one line, a paragraph on each side of the usage - +// has to come back whole, and a Flags block it cannot read has to be an error. +func TestTheCommandReferenceIsReadFromTheHelp(t *testing.T) { + canary := "tfg demo - do one thing.\n\nWhat it is for.\n\nUsage:\n tfg demo \n\nA note.\n\n" + + "Flags:\n -count int\n \thow many (default 1)\n -name string\n \tthe name (default \"files\")\n -w\twrite it back\n" + doc, err := parseCommandHelp("demo", "", canary) + want := site.CommandDoc{Name: "demo", Summary: "Do one thing.", About: []string{"What it is for."}, + Usage: []string{"tfg demo "}, Notes: []string{"A note."}, Flags: []site.FlagDoc{ + {Name: "count", Takes: "int", Default: "1", Text: "how many"}, + {Name: "name", Takes: "string", Default: "files", Text: "the name"}, + {Name: "w", Text: "write it back"}, + }} + if err != nil || !reflect.DeepEqual(doc, want) { + t.Fatalf("the canary help came back as %+v (%v), and it is %+v", doc, err, want) + } + if _, err := parseCommandHelp("demo", "", "tfg demo - x.\n\nUsage:\n tfg demo\n\nFlags:\n count int\n"); err == nil { + t.Fatal("a Flags block in a shape nothing reads was taken without an error") + } + + docs, _ := commandDocsAndRecipes(t, presetFactsFromTheProgram(t)) + for _, d := range docs { + if d.Summary == "" { + t.Errorf("tfg %s has no summary, so its row on the page would be blank", d.Name) + } + } + for _, d := range docs { + if d.Name != "generate" { + continue + } + read := map[string]bool{} + for _, f := range d.Flags { + read[f.Name] = true + } + if !maps.Equal(read, flagsOfGenerate(t)) { + t.Errorf("the reference reads the flags %v of generate and its help has %v", read, flagsOfGenerate(t)) + } + } +} + +// The English reference says something about every key of a recipe, every +// field of a manifest and every recipe of the gallery, and about nothing else. +// +// Its canary: an item without a sentence and a sentence about an item that is +// not there have to give two problems. +func TestTheReferenceDescribesEveryKeyFieldAndRecipe(t *testing.T) { + if got := describedBothWays("key", []string{"a", "b"}, map[string]string{"a": "x", "c": "y"}); len(got) != 2 { + t.Fatalf("the canary gave %d problem(s) and has two: %v", len(got), got) + } + root := rootLanguageOnDisk(t) + if root.Docs == nil { + t.Fatalf("the %s language file has no reference text, so the reference pages cannot be rendered", root.Code) + } + _, recipes := commandDocsAndRecipes(t, presetFactsFromTheProgram(t)) + var gallery []string + for _, r := range recipes { + if !r.Preset { + gallery = append(gallery, r.ID) + } + } + problems := describedBothWays("recipe key", recipe.Keys(), root.Docs.RecipeKeys) + problems = append(problems, describedBothWays("manifest field", manifestFieldsOf(), root.Docs.ManifestFields)...) + problems = append(problems, describedBothWays("recipe of the gallery", gallery, root.Docs.Recipes)...) + for _, p := range problems { + t.Error(p) + } +} + +// galleryRecipeProblems is what is wrong with one recipe of the gallery +// before it is run: it has to write into a folder of its own name, so two +// recipes run one after the other never write into one folder. +func galleryRecipeProblems(id string, body []byte) []string { + var r struct { + Output struct { + Dir string `yaml:"dir"` + } `yaml:"output"` + } + if err := yaml.Unmarshal(body, &r); err != nil { + return []string{id + " does not read as YAML: " + err.Error()} + } + if r.Output.Dir != "./"+id { + return []string{fmt.Sprintf("%s writes into %q, and a recipe of the gallery writes into ./%s", id, r.Output.Dir, id)} + } + return nil +} + +// Every recipe of the gallery is valid, makes files and writes into a folder of +// its own name. +// +// Its canary: a recipe that writes into a folder of another name has to be +// reported. +func TestEveryRecipeOfTheGalleryIsValidAndWritesToItsOwnFolder(t *testing.T) { + if got := galleryRecipeProblems("one", []byte("version: 1\noutput:\n dir: ./two\n")); len(got) != 1 { + t.Fatalf("the canary, a recipe writing into another folder, gave %d problem(s): %v", len(got), got) + } + _, recipes := commandDocsAndRecipes(t, presetFactsFromTheProgram(t)) + gallery := 0 + for _, r := range recipes { + if r.Files == 0 { + t.Errorf("the recipe %s makes no file, so the gallery would offer an empty set", r.ID) + } + if r.Preset { + continue + } + gallery++ + for _, p := range galleryRecipeProblems(r.ID, r.Body) { + t.Error(p) + } + file := filepath.Join(repoRoot(t), filepath.FromSlash(recipeGalleryDir), r.ID+".yaml") + if _, err := runQuietly("validate", file); err != nil { + t.Errorf("the recipe %s does not validate: %v", r.ID, err) + } + } + if gallery == 0 { + t.Errorf("%s holds no recipe, so the page that links to it would offer nothing", recipeGalleryDir) + } +} + +// rootLanguageOnDisk is the language served at the root. +func rootLanguageOnDisk(t *testing.T) site.Language { + t.Helper() + for _, l := range languagesOnDisk(t) { + if l.Dir == "" { + return l + } + } + t.Fatal("no language is served at the root") + return site.Language{} +} + +// untranslatedDocs is every page of the root language written in it alone +// that sits under the documentation hub. +func untranslatedDocs(root site.Language) []string { + var out []string + for _, p := range root.Pages { + if p.Untranslated && p.Parent == "docs" { + out = append(out, p.Key) + } + } + return out +} + +// Every translated hub says something about every English page under it, and +// about nothing else. +// +// The canary is the one of TestTheReferenceDescribesEveryKeyFieldAndRecipe, +// which this shares the comparison with. Here it is asked that the English +// pages exist at all, so the comparison cannot pass by comparing nothing. +func TestEveryLanguageLeadsToTheEnglishDocumentation(t *testing.T) { + langs := languagesOnDisk(t) + english := untranslatedDocs(rootLanguageOnDisk(t)) + if len(english) == 0 { + t.Fatal("no page under the documentation hub is marked untranslated, so this would compare nothing") + } + for _, l := range langs { + if l.Dir == "" { + if l.Docs != nil && len(l.Docs.Guides) != 0 { + t.Errorf("%s is served at the root and describes its own pages to itself in guides", l.Code) + } + continue + } + var guides map[string]site.GuideText + if l.Docs != nil { + guides = l.Docs.Guides + } + for _, p := range describedBothWays("English page", english, guides) { + t.Errorf("%s: %s", l.Code, p) + } + } +} diff --git a/internal/guard/sitelanguages_test.go b/internal/guard/sitelanguages_test.go index 4307685f..3c8b5e06 100644 --- a/internal/guard/sitelanguages_test.go +++ b/internal/guard/sitelanguages_test.go @@ -131,6 +131,21 @@ func TestEveryPageSaysWhichLanguageItIsAndWhereItsTranslationsAre(t *testing.T) title := regexp.MustCompile(`([^<]*)`) description := regexp.MustCompile(``) + untranslatedFiles := map[string]bool{} + for _, p := range root.Pages { + if p.Untranslated { + untranslatedFiles[strings.Trim(p.Slug, "/")+"/index.html"] = true + } + } + if len(untranslatedFiles) == 0 { + t.Fatal("no page is marked untranslated, so the rule for one is asked of nothing") + } + for file := range untranslatedFiles { + if _, ok := rendered[file]; !ok { + t.Errorf("%s is marked untranslated and was not rendered, so the rule for it is asked of nothing", file) + } + } + pages := map[string]map[string]string{} canonicals := map[string]string{} seenTitle, seenDescription := map[string]string{}, map[string]string{} @@ -158,13 +173,19 @@ func TestEveryPageSaysWhichLanguageItIsAndWhereItsTranslationsAre(t *testing.T) } pages[file] = found - for _, l := range s.Languages { + // A page written in the root language alone names itself and + // x-default, and nothing else, since it has no translation. + languages := s.Languages + if untranslatedFiles[file] { + languages = []site.Language{root} + } + for _, l := range languages { if _, ok := found[l.Code]; !ok { t.Errorf("%s does not name its %s translation, so a search engine is not told it exists", file, l.Code) } } - if _, ok := found["x-default"]; !ok || len(found) != len(s.Languages)+1 { - t.Errorf("%s names %d alternates, and the languages are %d plus x-default", file, len(found), len(s.Languages)) + if _, ok := found["x-default"]; !ok || len(found) != len(languages)+1 { + t.Errorf("%s names %d alternates, and the languages are %d plus x-default", file, len(found), len(languages)) } for _, field := range []struct { name string diff --git a/internal/guard/sitepresets_test.go b/internal/guard/sitepresets_test.go index 5a89684b..e026bb76 100644 --- a/internal/guard/sitepresets_test.go +++ b/internal/guard/sitepresets_test.go @@ -92,6 +92,8 @@ func siteProperty(p format.Property) site.Property { Unit: p.Unit, Choices: append([]string(nil), p.Choices...), Shape: p.Shape, + Default: p.Default, + Detail: p.Detail, } } diff --git a/internal/guard/toolversions_test.go b/internal/guard/toolversions_test.go index 4ad4a053..1217ea6a 100644 --- a/internal/guard/toolversions_test.go +++ b/internal/guard/toolversions_test.go @@ -90,6 +90,18 @@ func TestTheToolVersionCheckReadsNpmInstallAsACommand(t *testing.T) { `npm install --prefix "$RUNNER_TEMP/mailparser" mailparser@3.10.0`, map[string]string{"mailparser": "3.10.0"}, false}, {"a scoped pin after another command", `run: cd web && npm install @scope/pkg@1.2.3`, map[string]string{"@scope/pkg": "1.2.3"}, false}, + {"a quoted path that holds a semicolon", + `npm install --prefix "$RUNNER_TEMP/a;b" mailparser@3.10.0`, map[string]string{"mailparser": "3.10.0"}, false}, + {"a tarball named without a path", + `npm install fixture.tgz mailparser@3.10.0`, map[string]string{"mailparser": "3.10.0"}, false}, + {"a pin after a redirection", + `npm install >install.log 2>&1 mailparser@3.10.0`, map[string]string{"mailparser": "3.10.0"}, false}, + {"an install that names no version after a redirection", `npm install >install.log mailparser`, nil, true}, + {"a scoped package whose name ends like a tarball", `npm install @scope/fixture.tgz`, nil, true}, + {"a comment after the pin", + `npm install mailparser@3.10.0 # the version the tests read`, map[string]string{"mailparser": "3.10.0"}, false}, + {"a step name with an apostrophe that mentions npm install", + `- name: npm install can't reach the registry from here`, map[string]string{}, false}, {"an install that names no version", `npm install mailparser`, nil, true}, {"an install that names no version after run:", `- run: npm install --prefix x mailparser`, nil, true}, } { diff --git a/internal/site/docs.go b/internal/site/docs.go new file mode 100644 index 00000000..7265393f --- /dev/null +++ b/internal/site/docs.go @@ -0,0 +1,175 @@ +// This file holds the documentation: the hub at /docs/ and the pages under it, +// most of them written in English alone. +// +// The owner decided on 2026-11-24 that the documentation is English only, +// because reference text in twenty two languages cannot be kept true. The hub +// stays in every language, since search engines know its addresses, and leads +// a reader to the English pages with a line in their own language about each +// (docs/DOCS-SITE-2026-11-24.md section 4.1). + +package site + +import ( + "fmt" + "sort" +) + +// docsKey is the key of the documentation hub, the page every page of the +// documentation sits under. +const docsKey = "docs" + +// GuideText is what a translated hub says about one English page. +type GuideText struct { + Title string `json:"title"` + Text string `json:"text"` +} + +// DocLink is one page as the hub and the menu of the documentation list it. +type DocLink struct { + Key string + Title string + Text string + URL string + Current bool + // English marks a link from a translated page to a page written in + // English only, so a reader knows before following it. + English bool + // Anchors are the sections of the old single page of documentation that + // this page took over, so an address with one of them still lands on it. + Anchors []string +} + +// oldDocsAnchors are the sections /docs/ had until 2026-11-24, when it was one +// page, and the page that took each over. Links with these fragments were +// published for three months, so the hub keeps every one as the id of the +// card that leads on. +var oldDocsAnchors = map[string]string{ + "commands": "guide-commands", + "one-file": "guide-start", + "damage": "damage", + "recipes": "guide-recipes", + "expectations": "guide-recipes", + "manifest": "guide-manifest", + "presets": "presets", + "ci": "guide-commands", + "window": "guide-window", +} + +// anchorsOf is every old section that leads to the page with this key. +func anchorsOf(key string) []string { + var out []string + for anchor, to := range oldDocsAnchors { + if to == key { + out = append(out, anchor) + } + } + sort.Strings(out) + return out +} + +// docLinks is every page under the hub, in the order the root language lists +// them, as a reader of one language sees them. +// +// A page the language has is its own. A page written in English alone is the +// root language's, described by the line this language wrote about it, and a +// language without that line is an error rather than an English title on a +// translated hub. +func (s Site) docLinks(lang Language, current Page) ([]DocLink, error) { + root, ok := s.rootLanguage() + if !ok { + return nil, fmt.Errorf("no language is served at the root, so the documentation has no pages to list") + } + var out []DocLink + for _, p := range root.Pages { + if p.Parent != docsKey { + continue + } + if own, ok := find(lang, p.Key); ok { + out = append(out, DocLink{Key: own.Key, Title: own.Nav, Text: own.Description, URL: pageURL(lang, own), + Current: own.Key == current.Key, Anchors: anchorsOf(own.Key)}) + continue + } + text := lang.Docs.guide(p.Key) + if text.Title == "" || text.Text == "" { + return nil, fmt.Errorf("the English page %q has no title or line written in %s for the documentation hub", p.Key, lang.Code) + } + out = append(out, DocLink{Key: p.Key, Title: text.Title, Text: text.Text, URL: pageURL(root, p), + English: true, Anchors: anchorsOf(p.Key)}) + } + return out, nil +} + +// PagesOf is the pages with these keys in the language being rendered, as +// cards for the hub: the pages of the product the documentation leads to. +func (v view) PagesOf(keys ...string) ([]DocLink, error) { + out := make([]DocLink, 0, len(keys)) + for _, key := range keys { + p, ok := find(v.Lang, key) + if !ok { + return nil, fmt.Errorf("the %s page %q links to the page %q, which is not there", v.Lang.Code, v.Page.Key, key) + } + out = append(out, DocLink{Key: key, Title: p.Nav, Text: p.Description, URL: pageURL(v.Lang, p), Anchors: anchorsOf(key)}) + } + return out, nil +} + +// nearestIn is the page of another language a reader of an untranslated page +// is sent to: the closest page above it that the language has, or its home. +// +// The walk is bounded by the number of pages, so two pages naming each other +// as parent end it rather than loop. +func nearestIn(other, from Language, page Page) Page { + key := page.Parent + for range from.Pages { + if key == "" { + break + } + if mate, ok := find(other, key); ok { + return mate + } + up, ok := find(from, key) + if !ok { + break + } + key = up.Parent + } + return Page{Key: "index"} +} + +// checkUntranslated refuses a page marked untranslated anywhere but in the root +// language, and one that has a translation after all, since then the mark +// would hide the translation from search engines. +func checkUntranslated(langs []Language) error { + all := everyPage(langs) + languages := map[string]int{} + for _, x := range all { + languages[x.page.Key]++ + } + for _, x := range all { + switch { + case !x.page.Untranslated: + case x.lang.Dir != "": + return fmt.Errorf("the %s page %q is marked untranslated, and only a page of the language served at the root can be", x.lang.Code, x.page.Key) + case languages[x.page.Key] > 1: + return fmt.Errorf("the page %q is marked untranslated and has a translation, which the mark would hide", x.page.Key) + } + } + return nil +} + +// placed is one page in one language. +type placed struct { + lang Language + page Page +} + +// everyPage is every page of every language, as one list. +func everyPage(langs []Language) []placed { + var out []placed + for _, l := range langs { + for _, p := range l.Pages { + out = append(out, placed{lang: l, page: p}) + } + } + return out +} diff --git a/internal/site/languages.go b/internal/site/languages.go index 3be9efe2..f60acb2e 100644 --- a/internal/site/languages.go +++ b/internal/site/languages.go @@ -14,6 +14,7 @@ package site import ( "fmt" "regexp" + "strings" ) var ( @@ -49,7 +50,19 @@ func checkLanguages(langs []Language) error { if roots != 1 { return fmt.Errorf("%d languages are served at the root and exactly one has to be, because x-default points at it", roots) } - return nil + return checkUntranslated(langs) +} + +// addressablePath is a slug of one or more addressable parts joined by +// slashes, as docs/install, so a page written by hand can sit under the +// address of another. +func addressablePath(slug string) bool { + for _, part := range strings.Split(slug, "/") { + if !addressable.MatchString(part) { + return false + } + } + return true } // claimed remembers which language holds each value that has to be unique. @@ -88,8 +101,8 @@ func checkLanguage(l Language) error { } seen := map[string]string{} for _, p := range l.Pages { - if p.Slug != "" && !addressable.MatchString(p.Slug) { - return fmt.Errorf("the %s page %q has the slug %q, which cannot be part of an address - lower case letters, digits and single dashes can", l.Code, p.Key, p.Slug) + if p.Slug != "" && !addressablePath(p.Slug) { + return fmt.Errorf("the %s page %q has the slug %q, which cannot be part of an address - lower case letters, digits and single dashes can, in parts joined by slashes", l.Code, p.Key, p.Slug) } if other, taken := seen[p.Slug]; taken { return fmt.Errorf("the %s pages %q and %q share the address %q, so one would be written over the other", l.Code, other, p.Key, p.Slug) diff --git a/internal/site/reference.go b/internal/site/reference.go new file mode 100644 index 00000000..23d59129 --- /dev/null +++ b/internal/site/reference.go @@ -0,0 +1,327 @@ +// This file holds what the reference pages of the documentation show: every +// command with every flag, every key of a recipe, every field of a manifest, +// every setting of every format, and the recipes to download. +// +// Every list here comes from the program, and the page only adds a sentence +// beside each item. Those sentences are English, in the root language file +// alone, because the pages are (docs.go), and each one is looked up by the item +// it describes, so an item nobody wrote a sentence for stops the render rather +// than leaving a blank row. The other direction - a sentence about an item the +// program no longer has - is asked by the guards in internal/guard. + +package site + +import ( + "fmt" + "html/template" + "path" + "strings" +) + +// RecipesDir is where the recipes of the gallery are published, beside the +// page that lists them, with the presets in a folder of their own. +const RecipesDir = "recipes" + +// DocsFacts is what the documentation lists, read from the program. +// +// Commands is every command tfg --help prints, in the order it prints them, +// each as its own --help describes it. Taking the list from the help is the +// point: it is the text a visitor compares the page against, so agreeing +// with anything else would prove the wrong thing. RecipeKeys is every key +// recipe.Keys gives, Outcomes and Reasons the closed lists an expectation is +// written in, ManifestFields every field a manifest can carry by its dotted +// path, and Recipes every recipe of the gallery, the presets among them. +type DocsFacts struct { + Commands []CommandDoc + RecipeKeys []string + Outcomes []string + Reasons []string + ManifestFields []string + Recipes []Recipe +} + +// CommandNames is the names of the commands, in the order tfg --help prints +// them. +func (d DocsFacts) CommandNames() []string { + out := make([]string, len(d.Commands)) + for i, c := range d.Commands { + out[i] = c.Name + } + return out +} + +// DocsText is the text of the documentation in one language. +// +// A translated language has Guides alone: a line about each page written in +// the root language only, keyed by the page, for the hub and its menu. The +// root language has the rest, the sentences beside the lists of the English +// pages: RecipeKeys keyed by the dotted key as recipe.Keys gives it, +// ManifestFields by the dotted path of the field and Recipes by the id of a +// recipe of the gallery. +type DocsText struct { + Guides map[string]GuideText `json:"guides,omitempty"` + RecipeKeys map[string]string `json:"recipeKeys,omitempty"` + ManifestFields map[string]string `json:"manifestFields,omitempty"` + Recipes map[string]RecipeText `json:"recipes,omitempty"` +} + +// expanded runs the lines about the English pages through the facts, as every +// other text of a language is (view.go). The sentences of the reference are +// read as they are. +func (d *DocsText) expanded(through func(string) string) *DocsText { + if d == nil { + return nil + } + out := *d + out.Guides = make(map[string]GuideText, len(d.Guides)) + for key, g := range d.Guides { + out.Guides[key] = GuideText{Title: through(g.Title), Text: through(g.Text)} + } + return &out +} + +// RecipeText says what one recipe of the gallery is for. +type RecipeText struct { + Title string `json:"title"` + Text string `json:"text"` +} + +// CommandDoc is one command as tfg --help describes it. +// +// About is the paragraphs before the usage, Usage its lines as printed, and +// Notes the paragraphs after it. A command whose --help prints no help of its +// own, such as version, has a summary and nothing else. +type CommandDoc struct { + Name string + Summary string + About []string + Usage []string + Notes []string + Flags []FlagDoc +} + +// Anchor is the id of the command's section on the page. +func (c CommandDoc) Anchor() string { return "tfg-" + addressableName(c.Name) } + +// FlagDoc is one flag as the help prints it. Takes is the word after the name, +// such as string or int, and empty for a flag that takes no value. +type FlagDoc struct { + Name string + Takes string + Default string + Text string +} + +// Recipe is one recipe the gallery offers, with what a dry run of it counts. +type Recipe struct { + ID string + Preset bool + Body []byte + Files int + Bytes int64 + Formats []string +} + +// File is where the recipe is published under the root of the site. +func (r Recipe) File() string { + if r.Preset { + return path.Join(RecipesDir, "presets", r.ID+".yaml") + } + return path.Join(RecipesDir, r.ID+".yaml") +} + +// KeyRow is one key of a recipe, or one field of a manifest, with what it +// does. Target is set for a key of a target rather than of the whole recipe. +type KeyRow struct { + Key string + Text template.HTML + Target bool +} + +// guide is the line about one English page, empty when there is none. +func (d *DocsText) guide(key string) GuideText { + if d == nil { + return GuideText{} + } + return d.Guides[key] +} + +// docsText is the text of the documentation in the language, or an error +// naming what asked for it on a language that has none. +func docsText(v view) (*DocsText, error) { + if v.Lang.Docs == nil { + return nil, fmt.Errorf("the %s page %q shows reference text and the %s language file has none", v.Lang.Code, v.Page.Key, v.Lang.Code) + } + return v.Lang.Docs, nil +} + +// RecipeKeyRows is every key a recipe accepts, in the order recipe.Keys gives +// them, with what each does. +func (v view) RecipeKeyRows() ([]KeyRow, error) { + ref, err := docsText(v) + if err != nil { + return nil, err + } + out := make([]KeyRow, 0, len(v.Facts.Docs.RecipeKeys)) + for _, k := range v.Facts.Docs.RecipeKeys { + text, ok := ref.RecipeKeys[k] + if !ok || text == "" { + return nil, fmt.Errorf("the recipe key %q has no sentence in the %s reference", k, v.Lang.Code) + } + out = append(out, KeyRow{Key: k, Text: withCode(text), Target: strings.HasPrefix(k, "targets.")}) + } + return out, nil +} + +// ManifestRows is every field a manifest can carry, with what it holds. +func (v view) ManifestRows() ([]KeyRow, error) { + ref, err := docsText(v) + if err != nil { + return nil, err + } + out := make([]KeyRow, 0, len(v.Facts.Docs.ManifestFields)) + for _, f := range v.Facts.Docs.ManifestFields { + text, ok := ref.ManifestFields[f] + if !ok || text == "" { + return nil, fmt.Errorf("the manifest field %q has no sentence in the %s reference", f, v.Lang.Code) + } + out = append(out, KeyRow{Key: f, Text: withCode(text)}) + } + return out, nil +} + +// SettingDoc is one setting of a format as the page of format settings lists +// it, in the registry's own words. +type SettingDoc struct { + Name string + Takes template.HTML + Default template.HTML + Detail template.HTML +} + +// entities writes every character above ASCII in an HTML string as a numeric +// reference, which the browser shows as the character. +// +// The English pages are held to ASCII (TestTranslatedTextStaysOnTheTranslatedPages), +// and the registry's own words carry a few such characters - the default text +// of a placeholder picture is "{width} x {height}" with a multiplication sign. +// They are the program's text, so they are shown as they are rather than +// rewritten. +func entities(h template.HTML) template.HTML { + var b strings.Builder + for _, r := range string(h) { + if r > 127 { + fmt.Fprintf(&b, "&#%d;", r) + continue + } + b.WriteRune(r) + } + return template.HTML(b.String()) //nolint:gosec // escaped before, and a reference is no markup +} + +// FormatSettings is one format and every setting it takes. +type FormatSettings struct { + ID string + Name string + Settings []SettingDoc +} + +// FormatSettingsList is every format that takes settings, in the order the +// registry lists them. +func (v view) FormatSettingsList() ([]FormatSettings, error) { + var out []FormatSettings + for _, f := range v.Facts.WithProperties() { + settings, err := settingDocs(v, f) + if err != nil { + return nil, err + } + out = append(out, FormatSettings{ID: f.ID, Name: f.Name, Settings: settings}) + } + return out, nil +} + +// settingDocs is every setting of one format, in the registry's words. +func settingDocs(v view, f Format) ([]SettingDoc, error) { + out := make([]SettingDoc, 0, len(f.Properties)) + for _, p := range f.Properties { + takes, err := v.AllowedOf(p) + if err != nil { + return nil, err + } + if p.Detail == "" { + return nil, fmt.Errorf("the setting %s of %s has no description in the registry, so its row would be blank", p.Name, f.ID) + } + out = append(out, SettingDoc{Name: p.Name, Takes: entities(withCode(takes)), + Default: entities(template.HTML(template.HTMLEscapeString(p.Default))), Detail: entities(withCode(p.Detail))}) //nolint:gosec // escaped here + } + return out, nil +} + +// RecipeRow is one recipe as the gallery lists it. +type RecipeRow struct { + ID string + Title string + Text string + URL string + File string + Page string + Files int + Bytes string + Formats []string +} + +// GalleryRecipes is the recipes of the gallery, described in the reference +// text, in the order the program gives them. +func (v view) GalleryRecipes() ([]RecipeRow, error) { return recipeRows(v, false) } + +// PresetRecipes is every preset as a recipe, described by its own title and +// question, each leading to the page of the preset as well. +func (v view) PresetRecipes() ([]RecipeRow, error) { return recipeRows(v, true) } + +// recipeRows is the recipes of one kind as rows. +func recipeRows(v view, presets bool) ([]RecipeRow, error) { + ref, err := docsText(v) + if err != nil { + return nil, err + } + var out []RecipeRow + for _, r := range v.Facts.Docs.Recipes { + if r.Preset != presets { + continue + } + row := RecipeRow{ID: r.ID, URL: "/" + r.File(), File: path.Base(r.File()), Files: r.Files, Bytes: grouped(r.Bytes), Formats: r.Formats} + if err := describeRecipe(v, &row, r, ref); err != nil { + return nil, err + } + out = append(out, row) + } + if len(out) == 0 { + return nil, fmt.Errorf("the %s page %q lists recipes and there are none, so it would offer nothing", v.Lang.Code, v.Page.Key) + } + return out, nil +} + +// describeRecipe fills in the words of one row: a preset is described by its +// own title and question and leads to its page, a recipe of the gallery by the +// reference text. +func describeRecipe(v view, row *RecipeRow, r Recipe, ref *DocsText) error { + if r.Preset { + text, ok := v.Lang.Presets[r.ID] + page, found := find(v.Lang, presetKey(r.ID)) + if !ok || !found { + return fmt.Errorf("the preset %q is offered as a recipe and has no %s words or page", r.ID, v.Lang.Code) + } + row.Title, row.Text, row.Page = text.Title, text.Question, pageURL(v.Lang, page) + return nil + } + text, ok := ref.Recipes[r.ID] + if !ok || text.Title == "" || text.Text == "" { + return fmt.Errorf("the recipe %q has no title or description in the %s reference", r.ID, v.Lang.Code) + } + row.Title, row.Text = text.Title, text.Text + return nil +} + +// addressableName turns a command name such as "recipe fmt" into a part of an +// address. +func addressableName(name string) string { return strings.ReplaceAll(name, " ", "-") } diff --git a/internal/site/render.go b/internal/site/render.go index 603549e4..420476cc 100644 --- a/internal/site/render.go +++ b/internal/site/render.go @@ -92,6 +92,14 @@ func (s Site) Render() (map[string][]byte, error) { if len(s.Facts.Samples) > 0 { out[SamplesDir+"/SHA256SUMS"] = s.sampleSums() } + for _, r := range s.Facts.Docs.Recipes { + // The id becomes a path on disk and an address, and nothing before + // this asks what it looks like. + if !addressable.MatchString(r.ID) { + return nil, fmt.Errorf("the recipe %q cannot be part of an address - an id of lower case letters, digits and single dashes can", r.ID) + } + out[r.File()] = r.Body + } out["sitemap.xml"] = s.sitemap() out["robots.txt"] = s.robots() out["CNAME"] = []byte(s.Host() + "\n") @@ -184,6 +192,13 @@ func (s Site) viewFor(lang Language, page Page) (view, error) { } for _, other := range s.Languages { mate, ok := find(other, page.Key) + if !ok && page.Untranslated { + // No alternate, since there is none. The menu still leads the + // reader somewhere in their language. + near := nearestIn(other, lang, page) + v.Switches = append(v.Switches, Switch{Name: other.Name, URL: pageURL(other, near), Code: other.Code, Locale: other.Locale, Elsewhere: true}) + continue + } if !ok { return view{}, fmt.Errorf("the %s page %q has no %s translation, so its language link would lead nowhere", lang.Code, page.Key, other.Code) } @@ -197,6 +212,13 @@ func (s Site) viewFor(lang Language, page Page) (view, error) { v.Alternates = append(v.Alternates, Alternate{Lang: "x-default", URL: s.Origin() + pageURL(root, mate)}) } } + if page.Key == docsKey || page.Parent == docsKey { + docs, err := s.docLinks(lang, page) + if err != nil { + return view{}, err + } + v.Docs = docs + } return v, nil } @@ -400,9 +422,16 @@ func funcs() template.FuncMap { return template.FuncMap{ "join": strings.Join, "sorted": sortedStrings, + "ascii": asciiText, } } +// asciiText is text from the program on a page held to ASCII: escaped, with +// every character above ASCII as a numeric reference (entities). +func asciiText(s string) template.HTML { + return entities(template.HTML(template.HTMLEscapeString(s))) //nolint:gosec // escaped here +} + // sortedStrings returns a sorted copy, so a template never sorts in place. func sortedStrings(in []string) []string { out := append([]string(nil), in...) diff --git a/internal/site/site.go b/internal/site/site.go index 2fd1b466..d76bf783 100644 --- a/internal/site/site.go +++ b/internal/site/site.go @@ -45,6 +45,10 @@ type Property struct { // states it in English. Without it a text setting is described as "text", // which says nothing about the value it wants. Shape string + // Default and Detail are the registry's own, in English, and only the + // page of format settings shows them, which is written in English alone. + Default string + Detail string } // Format is one entry of the registry, flattened for display. @@ -170,11 +174,10 @@ type Facts struct { // about them cannot leave one out. Tools []string - // Commands is what tfg --help prints, in the order it prints it, read out - // of that help rather than out of a list beside it. Taking it from the - // help is the point: it is the text a visitor is comparing the page - // against, so agreeing with anything else would prove the wrong thing. - Commands []string + // Docs is what the documentation lists: every command tfg --help prints + // and its own help, the keys of a recipe, the fields of a manifest and the + // recipes of the gallery (reference.go). + Docs DocsFacts // Year is fixed rather than taken from the clock. A footer that rendered // the current year would make the committed pages differ from freshly @@ -247,6 +250,12 @@ type Page struct { // code, and a page written by hand may name its own in site.json. Parent string `json:"parent,omitempty"` + // Untranslated marks a page written in the root language alone, as the + // pages of the documentation are (docs.go). It names no translation to a + // search engine, and its language menu leads a reader of another language + // to the closest page above it that their language has. + Untranslated bool `json:"untranslated,omitempty"` + // The two below are never written in site.json. They are set on the // pages made from a list, and say which content file holds their text and // which item of the list they are about. @@ -292,6 +301,9 @@ type Language struct { Tools map[string]string `json:"tools"` Pages []Page `json:"pages"` Faq []QA `json:"faq"` + + // Docs is the text of the documentation in this language (reference.go). + Docs *DocsText `json:"docs,omitempty"` } // Site is everything needed to render. @@ -333,11 +345,16 @@ type NavItem struct { } // Switch is the link to this page in another language. +// +// Elsewhere says the link leads to another page, because this one is not +// translated. Such a link is no alternate of the page, so it carries no +// rel=alternate and no og:locale:alternate. type Switch struct { - Name string - URL string - Code string - Locale string + Name string + URL string + Code string + Locale string + Elsewhere bool } // Origin is the address the site is served from, without a trailing slash. diff --git a/internal/site/view.go b/internal/site/view.go index 04334a14..a03c2630 100644 --- a/internal/site/view.go +++ b/internal/site/view.go @@ -72,6 +72,7 @@ func (l Language) expand(f Facts) (Language, error) { out.Outcomes = everyValue(l.Outcomes) out.Damages = everyValue(l.Damages) out.Tools = everyValue(l.Tools) + out.Docs = l.Docs.expanded(through) if l.Presets != nil { out.Presets = make(map[string]PresetText, len(l.Presets)) for id, text := range l.Presets { @@ -112,6 +113,9 @@ type view struct { // Up is the page this one sits under, for the link back to it and the // middle step of the breadcrumb. Nil for a page in the header. Up *NavItem + // Docs is every page of the documentation, for the hub and for the menu + // on each page under it. Empty on every other page. + Docs []DocLink } // Word looks up a piece of interface text. @@ -156,14 +160,15 @@ func (v view) Endings() ([]Ending, error) { // name - so an eleventh command longer than the tenth widens the column by // itself instead of leaving a template to be remembered. func (v view) CommandList() ([]Command, error) { + names := v.Facts.Docs.CommandNames() widest := 0 - for _, name := range v.Facts.Commands { + for _, name := range names { if len(name) > widest { widest = len(name) } } - out := make([]Command, 0, len(v.Facts.Commands)) - for _, name := range v.Facts.Commands { + out := make([]Command, 0, len(names)) + for _, name := range names { summary, ok := v.Lang.Commands[name] if !ok { return nil, fmt.Errorf("the command %q has no summary written in %s", name, v.Lang.Code) diff --git a/web/assets/site.css b/web/assets/site.css index 6b90b60e..a892cb58 100644 --- a/web/assets/site.css +++ b/web/assets/site.css @@ -496,6 +496,67 @@ figcaption { margin-bottom: 0; } +/* ------------------------------------------------------ documentation menu */ + +/* The pages of the documentation, on every page under the hub. A row of short + * links that wraps, so a phone needs no script and no second layout. */ +.docsmenu { + margin: 0 0 32px; + padding-bottom: 16px; + border-bottom: 1px solid var(--border-soft); +} + +.docsmenu ul { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin: 0; + padding: 0; + list-style: none; +} + +.docsmenu a { + display: inline-block; + color: var(--text-dim); + text-decoration: none; + padding: 5px 10px; + border-radius: 8px; + font-size: 14px; + background: var(--surface); +} + +.docsmenu a:hover, +.docsmenu a[aria-current] { + color: var(--text); + background: var(--surface-3); +} + +/* Beside a link from a translated page to a page written in English only, so + * the reader knows before following it. */ +.tag { + display: inline-block; + margin-inline-start: 6px; + padding: 0 5px; + border: 1px solid var(--border); + border-radius: 4px; + font-size: 11px; + font-weight: 600; + letter-spacing: 0.04em; + color: var(--muted); + vertical-align: middle; +} + +/* A screen of the window on the page about it: real size on a wide screen, + * never wider than the column. */ +.shot img { + display: block; + width: 100%; + max-width: 560px; + height: auto; + border: 1px solid var(--border-soft); + border-radius: var(--radius); +} + /* ------------------------------------------------------------------- lists */ ul.plain { @@ -826,6 +887,15 @@ pre code { width: 100%; } + /* A file name or a command in a sentence can be wider than a phone, and a + * span that cannot break pushes the page sideways, the same as in a note. + * On a wide screen code keeps to one line. */ + main p code, + main li code { + white-space: normal; + overflow-wrap: anywhere; + } + .footer-inner { grid-template-columns: 1fr; gap: 26px; diff --git a/web/content/ar/docs.html b/web/content/ar/docs.html index 06dc12fa..7c4b5f28 100644 --- a/web/content/ar/docs.html +++ b/web/content/ar/docs.html @@ -1,273 +1,21 @@

التوثيق

- كل ما تفعله الأداة، مرتبًا على هيئة الأسئلة التي يأتي بها الناس فعلًا. ملف - README في المستودع هو المرجع الكامل ويطابق دائمًا الإصدار الذي - نزّلته. + كيف تثبّت tfg، وتنشئ أول ملفات الاختبار، وكل ما يأخذه البرنامج ويكتبه: كل أمر وكل خيار، وكل مفتاح في الوصفة، وكل حقل في البيان، وكل إعداد لكل صيغة. هذه الصفحات باللغة الإنجليزية، لأنها تُبنى من البرنامج نفسه في كل مرة يُبنى فيها الموقع، لذلك تقول دائمًا ما يفعله الإصدار الذي تنزّله.

-
-

ما الأوامر المتاحة؟

-

كل أمر يؤدي مهمة واحدة:

- {{ template "commandList" . }} -

- يضم tfg tool أدوات للملفات الموجودة لديك، مثل فحص أرشيف قبل فك ضغطه. وتشرح صفحة - الأدوات كل واحدة منها. -

-
- -
-

كيف أولّد ملفًا واحدًا بحجم دقيق؟

-

- حدد الصيغة والحجم ووجهة الملف. تُعدّ الأحجام بالمضاعفات 1024، فـ2mb تساوي 2097152 - بايتًا. وعدد البايتات المجرد يصلح أيضًا، فـ--size 10485761 يطلب هذا العدد بالضبط. -

-
tfg generate --format png --size 2mb --out ./out
-

الخيارات المفيدة في generate:

-
- - - - - - - - - - - - - - - - - -
الخيارما يفعله
--format <id>صيغة الملفات، مثل txt
--size <size>الحجم الدقيق لكل ملف، مثل 10mb أو عدد بايتات مجرد
--size-range <a-b>حجم يُسحب لكل ملف من نطاق، مثل 1kb-8kb. يأتي السحب من البذرة
--boundary <size>ثلاثة ملفات حول حد: أقل بايتًا واحدًا، والحد نفسه، وأكثر بايتًا واحدًا
--count <n>عدد الملفات المراد إنتاجها. الافتراضي 1
--name <template>قالب الاسم، مثل invoice_{index:04}.txt
--out <dir>المجلد الذي يُكتب فيه
--seed <n>بذرة التشغيل. البذرة نفسها تعطي البايتات نفسها
--set <k>=<v>إعداد صيغة، يمكن تكراره
--damage <name>إتلاف الملفات عمدًا، يمكن تكراره ويُطبَّق بالترتيب. شغّل tfg damage للاطلاع على القائمة
--expected <outcome>accept أو reject أو sanitize أو unspecified
--dry-runعدّ وأظهر، ولا تكتب شيئًا إطلاقًا
--jsonاكتب البيان إلى المخرج القياسي
-
-
- -
-

كيف أصنع ملفًا تالفًا عمدًا؟

-

- كل ملف آخر تكتبه هذه الأداة صحيح بحكم بنائه، وهذا يجيب عن اثنين من ثلاثة أسئلة يطرحها مدقق الرفع. - أما --damage فيجيب عن الثالث: هل يُفتح الملف أصلًا. يُنتَج الملف بشكل طبيعي ثم - يُتلف، فيبقى بالحجم الذي طلبته. -

-
tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
-tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
-

- تُكتب الإعدادات بعد نقطتين. يمكن تكرار الخيار، وترتيب كتابتها هو ترتيب تطبيقها. يسرد tfg - damage ما يستطيعه هذا الإصدار وما يقبله كل نوع. -

-

في الوصفة يكون المفتاح قائمة، من أسماء أو من إعدادات:

-
targets:
-  - id: broken
-    format: png
-    count: 5
-    size: 2mb
-    damage:
-      - zero-head
-      - type: zero-head
-        bytes: 16
-

- يحصل الملف التالف على expected: reject في البيان، مع تسجيل الإتلاف بجانبه. يُرفض أمران - قبل كتابة أي شيء، لأن كلًّا منهما كان سيضع على القرص ملفًا يصفه البيان وصفًا خاطئًا: -

-
    -
  • ملف أصغر مما يحتاجه الإتلاف، لأنه كان سيخرج دون تغيير
  • -
  • - expected: accept بجانب إتلاف، لأن لا شيء يمكن أن يحققه. اكتب sanitize إن - كان المقصود أن يصلح النظام قيد الاختبار الملف، أو unspecified إن كان هذا هو - السؤال الذي تطرحه -
  • -
-

- أما الثالث فلا يمكن معرفته مسبقًا. إذا نُفّذ إتلاف ولم يحرّك أي بايت، يُسقَط ذلك الملف بدل كتابته، - ويستمر التشغيل ويذكر أي ملف كان، وينتهي برمز الخروج الجزئي. -

-

- خطوة بخطوة، مع اختبار يقرأ البيان: كيف تصنع ملفًا تالفًا - للاختبار. -

+
+

صفحات التوثيق

+ {{ template "linkCards" .Docs }}
-
-

كيف تبدو الوصفة؟

-

- الوصفة ملف YAML يصف تشغيلًا كاملًا. أودعها بجانب اختباراتك فتتوقف بيانات الاختبار عن كونها ملفات - ثنائية في مستودعك، ويستطيع أي شخص إعادة بنائها، بايتًا ببايت، من ملف بضع مئات من الأحرف. -

-
# fixtures.yaml
-version: 1
-seed: 7741
-
-defaults:
-  label: true
-
-targets:
-  - id: invoices
-    format: pdf
-    count: 25
-    size: 300kb
-    name: invoice_{index:04}.pdf
-    properties:
-      pages: 3
-      page_size: a4
-    expected: accept
-
-  - id: over_the_limit
-    format: png
-    count: 2
-    size: 12mb
-    expected:
-      outcome: reject
-      reason: size_limit
-
-  - id: bundle
-    format: zip
-    contains:
-      - format: txt
-        count: 200
-        size: 4kb
-
-output:
-  dir: ./fixtures
-  manifest: manifest.json
-
tfg validate fixtures.yaml
-tfg generate fixtures.yaml
-

- يحتاج كل هدف إلى واحد فقط من size أو size-range أو boundary - أو contains. اثنان خطأ، وعدم وجود أي منها خطأ كذلك. الوصفة غير الصالحة لا - تكتب أي ملف وتبلّغ عن كل المشكلات دفعة واحدة لا عن أولها فقط، وتسمّي كل مشكلة الإعداد - الذي تخصه. -

+
+

ما تفعله الأداة، حسب الموضوع

+ {{ template "linkCards" (.PagesOf "formats" "presets" "damage" "samples" "upload-tests" "ci" "exact-size") }}
-
-

كيف أصرّح بما يجب أن يفعله نظامي بملف ما؟

-

الصيغة القصيرة حين تكفي النتيجة، والطويلة حين يهم السبب:

-
expected: accept
-
expected:
-  outcome: reject
-  reason: size_limit
-

- النتائج هي accept وreject وsanitize - وunspecified. الأسباب قائمة مغلقة ليتمكن التقرير من التجميع بحسبها: - content_malformed وcount_limit وdimensions_limit - وduplicate وencoding_invalid وextension_rule - وfilename_invalid وfilename_too_long وfilename_traversal - وmalware_signature وmime_mismatch وnesting_depth - وnone وsize_limit وsize_zero. -

-

- يسمّي السبب القاعدة المعنية لا الحكم. ولهذا يمكن أن يقع السبب نفسه تحت أي من - النتيجتين: ملف أقل من الحد بايتًا واحدًا نتيجته accept، والقاعدة المعنية تبقى - size_limit. -

-
- -
-

ماذا يوجد في البيان؟

-

- يُكتب بجانب الملفات في نهاية كل تشغيل، بما في ذلك التشغيل الذي أُوقف. عنصر واحد لكل ملف: -

-
{
-  "manifest_version": "1.0",
-  "tool": { "name": "testing-files-generator", "version": "{{ .Facts.Version }}" },
-  "run": {
-    "id": "run_b359aa8d94",
-    "seed": 0,
-    "command": "tfg generate --format png --size 2mb --out ./out",
-    "platform": { "os": "windows", "arch": "amd64" },
-    "complete": true
-  },
-  "summary": {
-    "file_count": 1,
-    "total_bytes": 2097152,
-    "by_format": { "png": 1 },
-    "by_expected": { "unspecified": 1 }
-  },
-  "files": [
-    {
-      "path": "files_0001.png",
-      "bytes": 2097152,
-      "format": "png",
-      "fidelity": "full",
-      "determinism": "byte",
-      "seed": "8dc2d18c",
-      "hashes": { "sha256": "1a1f7c..." },
-      "properties": { "width": 640, "height": 480 },
-      "expected": {
-        "outcome": "unspecified",
-        "detail": "No expectation was declared for this file.",
-        "confidence": "policy_dependent"
-      }
-    }
-  ]
-}
-

- يُضاف recipe_hash حين يأتي التشغيل من وصفة، ويُضاف preset مع - overrides حين يأتي من إعداد مسبق، فيمكن دائمًا تتبّع البيان إلى ما أنتجه. -

-

- يحمل كل عنصر أيضًا target_id، وهو معرّف الهدف في الوصفة الذي أنتج الملف، ويحصي - summary.by_target الملفات التي انتهى إليها كل هدف. وهكذا يمكن فحص وصفة متعددة - الأهداف هدفًا هدفًا دون قراءة أسماء الملفات. -

-
- -
-

ما الإعداد المسبق؟

-

- مجموعة ملفات جاهزة تجيب عن سؤال اختبار شائع، فلا تحتاج إلى تصميم المجموعة بنفسك. الإعدادات المسبقة - وصفات عادية في جوهرها، ويطبع eject الوصفة لتعدّلها من هناك. لكل إعداد مسبق - صفحة خاصة تذكر ما يكتشفه عادةً، وما في المجموعة، وكل إعداد يقبله. -

- {{ template "presetsList" . }} -
tfg preset list
-tfg preset show size-boundaries
-tfg generate --preset size-boundaries --limit 10mb --out ./edges
-tfg preset eject size-boundaries > my.yaml
-

- يخبرك show بكلفة المجموعة قبل أن تبنيها، ويقول صراحةً حين يكون رقم ما قيمة مؤقتة منا لا - حدًّا منك. -

-
- -
-

ما معنى رموز الخروج؟

-

- لكل نهاية رمزها الخاص، وتذهب المخرجات المقروءة آليًا إلى المخرج القياسي، ولا يطبع التشغيل الفاشل - شيئًا هناك. الجدول عقد مجمّد، وتغيير معنى رمز يتطلب رفع الإصدار الرئيسي. -

- {{ template "exitCodesTable" . }} -
- name: build the fixtures
-  run: tfg generate fixtures.yaml --out ./fixtures
-
-- name: run the tests
-  run: pytest tests/
-
-- name: nothing moved
-  run: tfg verify ./fixtures/manifest.json
-

- التشغيل الموقوف بـ Ctrl+C يترك بيانًا ولا يترك أبدًا ملفًا مكتوبًا نصفه، لذا يمكن للمهمة التالية أن - تنظّف مهمة أُلغيت. -

-

- مسارات عمل جاهزة لـ GitHub Actions وGitLab CI: كيف تولّد ملفات - الاختبار في خط CI. -

-
- -
-

هل توجد نافذة سطح مكتب؟

-

- نعم، المحرك نفسه بنافذة فوقه، للاختبار الذي لا يُكتب له سكربت. وهي ليست نسخة مبتورة: يقارن اختبار - الواجهتين ميزةً ميزة، وكل ما تستطيع إحداهما فعله دون الأخرى يجب أن يُعلَن ويُبرَّر بدل أن - يتباعدا بصمت. -

+
+

ما زلت عالقًا؟

- الشاشات هي دفعة واحدة، والإعدادات المسبقة، وعدة دفعات معًا، وحول. تُظهر كلفة التشغيل قبل كتابة أي - شيء، وتبلّغ عن التقدم أثناء العمل، ويمكن إلغاؤها في منتصف الطريق دون ترك ملف مكتوب نصفه. لا تفتح - ملف وصفة بعد، فالوصفات شأن سطر الأوامر حاليًا، وتبني النافذة دفعاتها في النموذج. + يعرض tfg <command> --help في الطرفية ما يأخذه الأمر. كل رفض يذكر الإعداد المعني والسبب وقيمة ستنجح. إذا تصرّف شيء بخلاف ما تقوله صفحة هنا، أخبرنا. فهذا خطأ في الصفحة أو في البرنامج.

diff --git a/web/content/ar/site.json b/web/content/ar/site.json index d38e31a5..8516d8d3 100644 --- a/web/content/ar/site.json +++ b/web/content/ar/site.json @@ -139,7 +139,8 @@ "colSha256": "SHA-256", "colExpected": "المتوقع", "colTool": "الأداة", - "colQuestion": "السؤال الذي تجيب عنه" + "colQuestion": "السؤال الذي تجيب عنه", + "docsMenuLabel": "صفحات التوثيق" }, "endings": { "0": "عمل كل شيء.", @@ -387,5 +388,45 @@ "checksum": "هل هذا الملف هو ما يدّعي أنه هو؟", "checksum-check": "هل ما زال كل ملف كما يقول ملف مجاميعه الاختبارية؟", "checksum-write": "كيف سأعرف لاحقًا أن أيًّا من هذه الملفات لم يتغيّر؟" + }, + "docs": { + "guides": { + "guide-install": { + "title": "التثبيت", + "text": "نزّل لنظام Windows أو macOS أو Linux، وتحقق من الأرشيف، أو ثبّت عبر Docker أو npm أو pip أو Go." + }, + "guide-start": { + "title": "البدء", + "text": "أول ملف بحجم دقيق، ثم عشرة آلاف ملف، تُفحص وتُحذف وتُكتب وصفةً." + }, + "guide-commands": { + "title": "الأوامر", + "text": "كل أمر وكل خيار مع قيمته الافتراضية، وكل رموز الخروج." + }, + "guide-recipes": { + "title": "كتابة الوصفات", + "text": "كل مفتاح في الوصفة، والأحجام، وأسماء الملفات، وردود الفعل المتوقعة، والإتلاف، والأرشيفات، والإعدادات المسبقة." + }, + "recipes": { + "title": "معرض الوصفات", + "text": "وصفات جاهزة للتنزيل للرفع والاستيراد والأرشيفات والبريد والوسائط وCI والملفات الكثيرة." + }, + "guide-manifest": { + "title": "البيان", + "text": "كل حقل في manifest.json وكيف يقرؤه الاختبار." + }, + "guide-formats": { + "title": "إعدادات الصيغ", + "text": "كل إعداد لكل صيغة، مع القيم المقبولة والقيمة الافتراضية." + }, + "guide-frameworks": { + "title": "أُطر الاختبار", + "text": "الملفات داخل pytest وPlaywright وVitest وnode:test." + }, + "guide-window": { + "title": "تطبيق سطح المكتب", + "text": "نافذة البرنامج، شاشةً شاشة." + } + } } } diff --git a/web/content/cs/docs.html b/web/content/cs/docs.html index 62e7098d..0a214582 100644 --- a/web/content/cs/docs.html +++ b/web/content/cs/docs.html @@ -1,280 +1,21 @@

Dokumentace

- Vše, co nástroj dělá, uspořádané podle otázek, se kterými lidé skutečně přicházejí. - README v repozitáři je úplná reference a vždy odpovídá verzi, - kterou jste stáhli. + Jak nainstalovat tfg, vytvořit první testovací soubory a vše, co program přijímá a zapisuje: každý příkaz a každý přepínač, každý klíč receptu, každé pole manifestu a každé nastavení každého formátu. Tyto stránky jsou v angličtině, protože vznikají přímo z programu při každém sestavení webu, a proto vždy říkají, co dělá verze, kterou stahujete.

-
-

Jaké příkazy existují?

-

Každý dělá jednu věc:

- {{ template "commandList" . }} -

- tfg tool obsahuje nástroje pro soubory, které už máte, například kontrolu archivu před - rozbalením. Nástroje popisují každý z nich. -

-
- -
-

Jak vygeneruji jeden soubor přesné velikosti?

-

- Uveďte formát, velikost a kam soubor půjde. Velikosti se počítají po 1024, takže 2mb je - 2097152 bajtů. Funguje i prostý počet bajtů, takže --size 10485761 žádá přesně - tolik. -

-
tfg generate --format png --size 2mb --out ./out
-

Užitečné přepínače příkazu generate:

-
- - - - - - - - - - - - - - - - - -
PřepínačCo dělá
--format <id>formát souborů, například txt
--size <size>přesná velikost každého souboru, například 10mb nebo prostý počet bajtů
--size-range <a-b>velikost losovaná pro každý soubor z rozsahu, například 1kb-8kb. Losování vychází ze seedu
--boundary <size>tři soubory kolem limitu: o bajt pod, limit, o bajt nad
--count <n>kolik souborů vytvořit. Výchozí 1
--name <template>šablona názvu, například invoice_{index:04}.txt
--out <dir>adresář, do kterého se zapisuje
--seed <n>seed běhu. Stejný seed dává stejné bajty
--set <k>=<v>nastavení formátu, lze opakovat
--damage <name>záměrně soubory poškodit, lze opakovat a uplatňuje se v pořadí. Seznam získáte příkazem tfg damage
--expected <outcome>accept, reject, sanitize nebo unspecified
--dry-runspočítat a ukázat, nic nezapisovat
--jsonzapsat manifest na standardní výstup
-
-
- -
-

Jak vytvořím soubor, který je záměrně rozbitý?

-

- Každý jiný soubor, který tento nástroj zapíše, je správný z konstrukce, což odpovídá na dvě ze tří - otázek, které klade validátor nahrávání. --damage odpovídá na třetí - zda se soubor - vůbec otevře. Soubor se vytvoří normálně a pak se rozbije, takže má stále velikost, o kterou - jste požádali. -

-
tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
-tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
-

- Nastavení se zadávají za dvojtečku. Přepínač se opakuje a pořadí, v jakém je napíšete, je pořadí, v - jakém se uplatní. tfg damage vypíše, co tato verze umí a co která varianta přijímá. -

-

V receptu je klíč seznam, a to názvů nebo nastavení:

-
targets:
-  - id: broken
-    format: png
-    count: 5
-    size: 2mb
-    damage:
-      - zero-head
-      - type: zero-head
-        bytes: 16
-

- Poškozený soubor dostane v manifestu expected: reject a vedle toho zaznamenané - poškození. Dvě věci jsou odmítnuty dříve, než se cokoli zapíše, protože každá by jinak dala na - disk soubor, který manifest popisuje špatně: -

-
    -
  • soubor menší, než poškození potřebuje, protože by vyšel beze změny
  • -
  • - expected: accept vedle poškození, protože nic by to nemohlo splnit. Napište - sanitize, pokud má testovaný systém soubor opravit, nebo - unspecified, pokud je to právě ta otázka, kterou kladete -
  • -
-

- Třetí se předem zjistit nedá. Pokud se poškození provede a nepohne žádným bajtem, soubor se zahodí - místo zapsání - běh pokračuje, řekne, o který soubor šlo, a skončí s částečným návratovým kódem. -

-

- Krok za krokem, s testem, který čte manifest: jak - vytvořit poškozený soubor pro testy. -

+
+

Stránky dokumentace

+ {{ template "linkCards" .Docs }}
-
-

Jak vypadá recept?

-

- Recept je soubor YAML popisující celý běh. Commitujte ho vedle testů a fixtures přestanou být - binárkami ve vašem repozitáři - kdokoli je může bajt po bajtu znovu sestavit ze souboru o - několika stovkách znaků. -

-
# fixtures.yaml
-version: 1
-seed: 7741
-
-defaults:
-  label: true
-
-targets:
-  - id: invoices
-    format: pdf
-    count: 25
-    size: 300kb
-    name: invoice_{index:04}.pdf
-    properties:
-      pages: 3
-      page_size: a4
-    expected: accept
-
-  - id: over_the_limit
-    format: png
-    count: 2
-    size: 12mb
-    expected:
-      outcome: reject
-      reason: size_limit
-
-  - id: bundle
-    format: zip
-    contains:
-      - format: txt
-        count: 200
-        size: 4kb
-
-output:
-  dir: ./fixtures
-  manifest: manifest.json
-
tfg validate fixtures.yaml
-tfg generate fixtures.yaml
-

- Každý target potřebuje přesně jeden z klíčů size, size-range, - boundary nebo contains. Dva jsou chyba a žádný také. Neplatný recept - nezapíše žádné soubory a nahlásí všechny problémy najednou, ne jen první, každý - s názvem nastavení, kterého se týká. -

+
+

Co nástroj dělá, podle témat

+ {{ template "linkCards" (.PagesOf "formats" "presets" "damage" "samples" "upload-tests" "ci" "exact-size") }}
-
-

Jak deklaruji, co má můj systém se souborem udělat?

-

Krátká forma, když stačí výsledek, dlouhá forma, když záleží na důvodu:

-
expected: accept
-
expected:
-  outcome: reject
-  reason: size_limit
-

- Výsledky jsou accept, reject, sanitize a - unspecified. Důvody tvoří uzavřený seznam, aby podle nich mohl report seskupovat: - content_malformed, count_limit, dimensions_limit, - duplicate, encoding_invalid, extension_rule, - filename_invalid, filename_too_long, filename_traversal, - malware_signature, mime_mismatch, nesting_depth, - none, size_limit a size_zero. -

-

- Důvod pojmenovává pravidlo, o které jde, ne verdikt. Proto může stejný důvod stát - pod oběma výsledky - soubor o bajt pod limitem je accept a pravidlo, o které jde, - je stále size_limit. -

-
- -
-

Co obsahuje manifest?

-

- Zapisuje se vedle souborů na konci každého běhu, včetně přerušeného. Jedna položka na soubor: -

-
{
-  "manifest_version": "1.0",
-  "tool": { "name": "testing-files-generator", "version": "{{ .Facts.Version }}" },
-  "run": {
-    "id": "run_b359aa8d94",
-    "seed": 0,
-    "command": "tfg generate --format png --size 2mb --out ./out",
-    "platform": { "os": "windows", "arch": "amd64" },
-    "complete": true
-  },
-  "summary": {
-    "file_count": 1,
-    "total_bytes": 2097152,
-    "by_format": { "png": 1 },
-    "by_expected": { "unspecified": 1 }
-  },
-  "files": [
-    {
-      "path": "files_0001.png",
-      "bytes": 2097152,
-      "format": "png",
-      "fidelity": "full",
-      "determinism": "byte",
-      "seed": "8dc2d18c",
-      "hashes": { "sha256": "1a1f7c..." },
-      "properties": { "width": 640, "height": 480 },
-      "expected": {
-        "outcome": "unspecified",
-        "detail": "No expectation was declared for this file.",
-        "confidence": "policy_dependent"
-      }
-    }
-  ]
-}
-

- recipe_hash se přidá, když běh pochází z receptu, a preset s - overrides, když pochází z předvolby, takže manifest lze vždy dohledat k tomu, co ho - vytvořilo. -

-

- Každá položka nese také target_id, id targetu v receptu, který soubor vytvořil, a - summary.by_target počítá soubory, ke kterým každý target dospěl. Recept s více - targety lze tak kontrolovat target po targetu, aniž by se četly názvy souborů. -

-
- -
-

Co je předvolba?

-

- Hotová sada souborů, která odpovídá na běžnou testovací otázku, abyste sadu nemuseli navrhovat sami. - Předvolby jsou pod povrchem obyčejné recepty a eject recept vypíše, takže ho můžete - odtud upravit. Každá předvolba má vlastní stránku s tím, co obvykle - najde, co je v sadě a jaké nastavení přijímá. -

- {{ template "presetsList" . }} -
tfg preset list
-tfg preset show size-boundaries
-tfg generate --preset size-boundaries --limit 10mb --out ./edges
-tfg preset eject size-boundaries > my.yaml
-

- show vám řekne, kolik by sada stála, než ji sestavíte, a otevřeně řekne, když je číslo - naším zástupným údajem, a ne vaším limitem. -

-
- -
-

Co znamenají návratové kódy?

-

- Každý konec má svůj kód, strojově čitelný výstup jde na standardní výstup a neúspěšný běh tam - nevypíše nic. Tabulka je zmrazená smlouva - změna významu kódu vyžaduje novou hlavní verzi. -

- {{ template "exitCodesTable" . }} -
- name: build the fixtures
-  run: tfg generate fixtures.yaml --out ./fixtures
-
-- name: run the tests
-  run: pytest tests/
-
-- name: nothing moved
-  run: tfg verify ./fixtures/manifest.json
-

- Běh zastavený pomocí Ctrl+C po sobě stále zanechá manifest a nikdy nenechá napůl zapsaný soubor, - takže zrušenou úlohu může následující stále uklidit. -

-

- Hotová workflow pro GitHub Actions a GitLab CI: jak generovat - testovací soubory v CI pipeline. -

-
- -
-

Existuje desktopové okno?

-

- Ano, stejný motor s oknem navrch, pro testování, které se neskriptuje. Není to osekaná verze: test - porovnává obě rozhraní schopnost po schopnosti a cokoli, co umí jen jedno z nich, musí být - deklarováno a zdůvodněno, ne tiše se rozcházet. -

+
+

Stále si nevíte rady?

- Obrazovky jsou jedna dávka, předvolby, více dávek najednou a O aplikaci. Ukáže, kolik by běh stál, - než cokoli zapíše, hlásí průběh a lze ho zrušit uprostřed, aniž by zanechal napůl zapsaný - soubor. Soubor receptu zatím neotevře - recepty jsou zatím záležitostí příkazového řádku a okno - sestavuje své dávky ve formuláři. + tfg <command> --help v terminálu řekne, co příkaz přijímá. Každé odmítnutí jmenuje nastavení, kterého se týká, důvod a hodnotu, která bude fungovat. Pokud se něco chová jinak, než říká stránka, nahlaste to. Jde o chybu stránky nebo programu.

diff --git a/web/content/cs/site.json b/web/content/cs/site.json index 6bcc4e4e..e5270746 100644 --- a/web/content/cs/site.json +++ b/web/content/cs/site.json @@ -138,7 +138,8 @@ "colSha256": "SHA-256", "colExpected": "Očekáváno", "colTool": "Nástroj", - "colQuestion": "Na co odpovídá" + "colQuestion": "Na co odpovídá", + "docsMenuLabel": "Stránky dokumentace" }, "endings": { "0": "Vše fungovalo.", @@ -386,5 +387,45 @@ "checksum": "Je tento soubor tím, za který se vydává?", "checksum-check": "Odpovídá každý soubor stále tomu, co uvádí jeho soubor kontrolních součtů?", "checksum-write": "Jak později poznám, že se žádný z těchto souborů nezměnil?" + }, + "docs": { + "guides": { + "guide-install": { + "title": "Instalace", + "text": "Stažení pro Windows, macOS nebo Linux, kontrola archivu, nebo instalace přes Docker, npm, pip či Go." + }, + "guide-start": { + "title": "První kroky", + "text": "První soubor přesné velikosti, potom deset tisíc, zkontrolované, smazané a zapsané jako recept." + }, + "guide-commands": { + "title": "Příkazy", + "text": "Každý příkaz a každý přepínač s výchozí hodnotou a všechny návratové kódy." + }, + "guide-recipes": { + "title": "Psaní receptů", + "text": "Každý klíč receptu, velikosti, názvy souborů, očekávané reakce, poškození, archivy a presety." + }, + "recipes": { + "title": "Galerie receptů", + "text": "Hotové recepty ke stažení pro nahrávání, importy, archivy, e-maily, média, CI a hromadné soubory." + }, + "guide-manifest": { + "title": "Manifest", + "text": "Každé pole manifest.json a jak ho test čte." + }, + "guide-formats": { + "title": "Nastavení formátů", + "text": "Každé nastavení každého formátu s povolenými hodnotami a výchozí hodnotou." + }, + "guide-frameworks": { + "title": "Testovací frameworky", + "text": "Soubory v pytest, Playwright, Vitest a node:test." + }, + "guide-window": { + "title": "Desktopová aplikace", + "text": "Okno programu, obrazovka po obrazovce." + } + } } } diff --git a/web/content/de/docs.html b/web/content/de/docs.html index 7cc4ff79..51f8202f 100644 --- a/web/content/de/docs.html +++ b/web/content/de/docs.html @@ -1,289 +1,21 @@

Dokumentation

- Alles, was das Tool kann, geordnet nach den Fragen, mit denen die Leute tatsächlich kommen. Die - README im Repository ist die vollständige Referenz und passt immer - zu dem Build, den du heruntergeladen hast. + Wie Sie tfg installieren, Ihre ersten Testdateien erzeugen und alles, was das Programm annimmt und schreibt: jeder Befehl und jede Option, jeder Schlüssel eines Rezepts, jedes Feld des Manifests und jede Einstellung jedes Formats. Diese Seiten sind auf Englisch, weil sie bei jedem Bau der Website aus dem Programm selbst entstehen und deshalb immer sagen, was die Version tut, die Sie herunterladen.

-
-

Welche Befehle gibt es?

-

Jeder tut genau eine Sache:

- {{ template "commandList" . }} -

- tfg tool enthält die Werkzeuge für Dateien, die du schon hast, etwa die Prüfung eines - Archivs vor dem Entpacken. Die Seite Werkzeuge beschreibt jedes davon. -

-
- -
-

Wie erzeuge ich eine einzelne Datei in exakter Größe?

-

- Nenne das Format, die Größe und das Ziel. Größen zählen in 1024ern, 2mb sind also - 2097152 Bytes. Eine einfache Byte-Zahl funktioniert auch, --size 10485761 verlangt - also genau so viele. -

-
tfg generate --format png --size 2mb --out ./out
-

Die nützlichen Flags von generate:

-
- - - - - - - - - - - - - - - - - -
FlagWas es tut
--format <id>Format der Dateien, zum Beispiel txt
--size <size>exakte Größe jeder Datei, etwa 10mb oder eine einfache Byte-Zahl
--size-range <a-b>eine Größe, die pro Datei aus einem Bereich gezogen wird, etwa 1kb-8kb. Die Ziehung kommt aus dem Seed
--boundary <size>drei Dateien rund um ein Limit: ein Byte darunter, das Limit, ein Byte darüber
--count <n>wie viele Dateien erzeugt werden. Standard 1
--name <template>Namensvorlage, zum Beispiel invoice_{index:04}.txt
--out <dir>Verzeichnis, in das geschrieben wird
--seed <n>Seed des Laufs. Derselbe Seed ergibt dieselben Bytes
--set <k>=<v>eine Formateinstellung, wiederholbar
--damage <name>Dateien absichtlich beschädigen, wiederholbar und der Reihe nach angewendet. Mit tfg damage bekommst du die Liste
--expected <outcome>accept, reject, sanitize oder unspecified
--dry-runzählen und anzeigen, überhaupt nichts schreiben
--jsondas Manifest auf die Standardausgabe schreiben
-
-
- -
-

Wie erzeuge ich eine absichtlich kaputte Datei?

-

- Jede andere Datei, die dieses Tool schreibt, ist per Konstruktion korrekt, was zwei der drei Fragen - beantwortet, die ein Upload-Validator stellt. --damage beantwortet die dritte - - lässt sich die Datei überhaupt öffnen. Die Datei wird normal erzeugt und dann beschädigt, sie - hat also weiterhin die verlangte Größe. -

-
tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
-tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
-

- Einstellungen stehen hinter einem Doppelpunkt. Das Flag lässt sich wiederholen, und die Reihenfolge, - in der du sie schreibst, ist die Reihenfolge, in der sie angewendet werden. tfg - damage listet auf, was dieser Build kann und was jede Variante annimmt. -

-

In einem Rezept ist der Schlüssel eine Liste, aus Namen oder aus Einstellungen:

-
targets:
-  - id: broken
-    format: png
-    count: 5
-    size: 2mb
-    damage:
-      - zero-head
-      - type: zero-head
-        bytes: 16
-

- Eine beschädigte Datei bekommt im Manifest expected: reject, mit der daneben - festgehaltenen Beschädigung. Zwei Dinge werden abgelehnt, bevor etwas geschrieben wird, weil - sonst jeweils eine Datei auf die Platte käme, die das Manifest falsch beschreibt: -

-
    -
  • eine Datei, die kleiner ist, als die Beschädigung braucht, weil sie unverändert herauskäme
  • -
  • - expected: accept neben einer Beschädigung, weil es keine Datei geben kann, die das - erfüllt. Schreibe sanitize, wenn das getestete System die Datei reparieren soll, - oder unspecified, wenn genau das die Frage ist, die du stellst -
  • -
-

- Eine dritte lässt sich nicht im Voraus wissen. Wenn eine Beschädigung läuft und kein Byte verändert, - wird diese Datei verworfen statt geschrieben - der Lauf macht weiter, sagt, um welche Datei es - ging, und endet mit dem Exit-Code für teilweise erfolgreiche Läufe. -

-

- Schritt für Schritt, mit einem Test, der das Manifest liest: - So erzeugen Sie eine beschädigte Datei zum Testen. -

+
+

Seiten der Dokumentation

+ {{ template "linkCards" .Docs }}
-
-

Wie sieht ein Rezept aus?

-

- Ein Rezept ist eine YAML-Datei, die einen ganzen Lauf beschreibt. Checke sie neben deinen Tests ein, - und die Fixtures sind keine Binärdateien mehr in deinem Repository - jeder kann sie Byte für - Byte aus einer Datei von wenigen hundert Zeichen neu erzeugen. -

-
# fixtures.yaml
-version: 1
-seed: 7741
-
-defaults:
-  label: true
-
-targets:
-  - id: invoices
-    format: pdf
-    count: 25
-    size: 300kb
-    name: invoice_{index:04}.pdf
-    properties:
-      pages: 3
-      page_size: a4
-    expected: accept
-
-  - id: over_the_limit
-    format: png
-    count: 2
-    size: 12mb
-    expected:
-      outcome: reject
-      reason: size_limit
-
-  - id: bundle
-    format: zip
-    contains:
-      - format: txt
-        count: 200
-        size: 4kb
-
-output:
-  dir: ./fixtures
-  manifest: manifest.json
-
tfg validate fixtures.yaml
-tfg generate fixtures.yaml
-

- Jedes Target braucht genau eines von size, size-range, - boundary oder contains. Zwei davon sind ein Fehler, und keines - ebenfalls. Ein ungültiges Rezept schreibt überhaupt keine Dateien und meldet - alle Probleme auf einmal statt nur das erste, jedes mit der Einstellung, um die es geht. -

+
+

Was das Werkzeug tut, nach Thema

+ {{ template "linkCards" (.PagesOf "formats" "presets" "damage" "samples" "upload-tests" "ci" "exact-size") }}
-
-

Wie lege ich fest, was mein System mit einer Datei tun soll?

-

Kurzform, wenn das Ergebnis reicht, Langform, wenn der Grund zählt:

-
expected: accept
-
expected:
-  outcome: reject
-  reason: size_limit
-

- Die Ergebnisse sind accept, reject, sanitize und - unspecified. Die Gründe sind eine geschlossene Liste, damit ein Report danach - gruppieren kann: content_malformed, count_limit, - dimensions_limit, duplicate, encoding_invalid, - extension_rule, filename_invalid, filename_too_long, - filename_traversal, malware_signature, mime_mismatch, - nesting_depth, none, size_limit und - size_zero. -

-

- Ein Grund benennt die Regel, um die es geht, nicht das Urteil. Deshalb kann - derselbe Grund unter beiden Ergebnissen stehen - eine Datei ein Byte unter einem Limit ist - accept, und die Regel, um die es geht, ist trotzdem size_limit. -

-
- -
-

Was steht im Manifest?

-

- Es wird am Ende jedes Laufs neben die Dateien geschrieben, auch bei einem unterbrochenen Lauf. Ein - Eintrag pro Datei: -

-
{
-  "manifest_version": "1.0",
-  "tool": { "name": "testing-files-generator", "version": "{{ .Facts.Version }}" },
-  "run": {
-    "id": "run_b359aa8d94",
-    "seed": 0,
-    "command": "tfg generate --format png --size 2mb --out ./out",
-    "platform": { "os": "windows", "arch": "amd64" },
-    "complete": true
-  },
-  "summary": {
-    "file_count": 1,
-    "total_bytes": 2097152,
-    "by_format": { "png": 1 },
-    "by_expected": { "unspecified": 1 }
-  },
-  "files": [
-    {
-      "path": "files_0001.png",
-      "bytes": 2097152,
-      "format": "png",
-      "fidelity": "full",
-      "determinism": "byte",
-      "seed": "8dc2d18c",
-      "hashes": { "sha256": "1a1f7c..." },
-      "properties": { "width": 640, "height": 480 },
-      "expected": {
-        "outcome": "unspecified",
-        "detail": "No expectation was declared for this file.",
-        "confidence": "policy_dependent"
-      }
-    }
-  ]
-}
-

- Ein recipe_hash kommt hinzu, wenn der Lauf aus einem Rezept stammt, und - preset mit overrides, wenn er aus einem Preset stammt, sodass sich ein - Manifest immer auf das zurückführen lässt, was es erzeugt hat. -

-

- Jeder Eintrag trägt außerdem target_id, die ID des Targets im Rezept, das die Datei - erzeugt hat, und summary.by_target zählt, auf wie viele Dateien jedes Target kam. - Ein Rezept mit mehreren Targets lässt sich so Target für Target prüfen, ohne Dateinamen zu - lesen. -

-
- -
-

Was ist ein Preset?

-

- Ein fertiges Set aus Dateien, das eine gängige Testfrage beantwortet, damit du das Set nicht selbst - entwerfen musst. Presets sind darunter ganz normale Rezepte, und eject gibt das - Rezept aus, damit du es von dort aus bearbeiten kannst. Jedes Preset hat - eine eigene Seite mit dem, was es meist findet, was im Set steckt und - welche Einstellungen es kennt. -

- {{ template "presetsList" . }} -
tfg preset list
-tfg preset show size-boundaries
-tfg generate --preset size-boundaries --limit 10mb --out ./edges
-tfg preset eject size-boundaries > my.yaml
-

- show sagt dir, was das Set kosten würde, bevor du es baust, und sagt - unmissverständlich, wenn eine Zahl ein Platzhalter von uns statt ein Limit von dir ist. -

-
- -
-

Was bedeuten die Exit-Codes?

-

- Jedes Ende hat einen eigenen Code, maschinenlesbare Ausgabe geht auf die Standardausgabe, und ein - fehlgeschlagener Lauf gibt dort nichts aus. Die Tabelle ist ein eingefrorener Vertrag - die - Bedeutung eines Codes zu ändern erfordert einen Major-Versionssprung. -

- {{ template "exitCodesTable" . }} -
- name: build the fixtures
-  run: tfg generate fixtures.yaml --out ./fixtures
-
-- name: run the tests
-  run: pytest tests/
-
-- name: nothing moved
-  run: tfg verify ./fixtures/manifest.json
-

- Ein mit Strg+C gestoppter Lauf hinterlässt trotzdem ein Manifest und nie eine halb geschriebene - Datei, sodass ein abgebrochener Job vom nächsten noch aufgeräumt werden kann. -

-

- Fertige Workflows für GitHub Actions und GitLab CI: So erzeugen Sie - Testdateien in einer CI-Pipeline. -

-
- -
-

Gibt es ein Desktop-Fenster?

-

- Ja, dieselbe Engine mit einem Fenster davor, für das Testen, das nicht skriptbar ist. Es ist keine - abgespeckte Version: Ein Test vergleicht die beiden Oberflächen Fähigkeit für Fähigkeit, und - alles, was nur eine von beiden kann, muss deklariert und begründet werden, statt unbemerkt - auseinanderzudriften. -

+
+

Immer noch nicht weiter?

- Die Bildschirme sind ein Stapel, Presets, mehrere Stapel gleichzeitig und Info. Es zeigt, was ein - Lauf kosten würde, bevor etwas geschrieben wird, meldet den Fortschritt während des Laufs und - lässt sich mittendrin abbrechen, ohne eine halb geschriebene Datei zu hinterlassen. Eine - Rezeptdatei öffnet es noch nicht - Rezepte gibt es vorerst nur auf der Kommandozeile, und das - Fenster baut seine Stapel im Formular. + tfg <command> --help zeigt im Terminal, was ein Befehl annimmt. Jede Ablehnung nennt die Einstellung, um die es geht, den Grund und einen Wert, der funktioniert. Wenn sich etwas anders verhält, als eine Seite hier sagt, melden Sie es. Dann ist die Seite oder das Programm fehlerhaft.

diff --git a/web/content/de/site.json b/web/content/de/site.json index f63c702e..3e17061f 100644 --- a/web/content/de/site.json +++ b/web/content/de/site.json @@ -138,7 +138,8 @@ "colSha256": "SHA-256", "colExpected": "Erwartet", "colTool": "Werkzeug", - "colQuestion": "Was es beantwortet" + "colQuestion": "Was es beantwortet", + "docsMenuLabel": "Seiten der Dokumentation" }, "endings": { "0": "Alles hat funktioniert.", @@ -386,5 +387,45 @@ "checksum": "Ist diese Datei die, die sie zu sein vorgibt?", "checksum-check": "Ist jede Datei noch so, wie ihre Prüfsummendatei sagt?", "checksum-write": "Woran erkenne ich später, dass sich keine dieser Dateien geändert hat?" + }, + "docs": { + "guides": { + "guide-install": { + "title": "Installation", + "text": "Für Windows, macOS oder Linux herunterladen, das Archiv prüfen oder mit Docker, npm, pip oder Go installieren." + }, + "guide-start": { + "title": "Erste Schritte", + "text": "Die erste Datei mit exakter Größe, dann zehntausend, geprüft, entfernt und als Rezept festgehalten." + }, + "guide-commands": { + "title": "Befehle", + "text": "Jeder Befehl und jede Option mit ihrem Standardwert, dazu alle Exit-Codes." + }, + "guide-recipes": { + "title": "Rezepte schreiben", + "text": "Jeder Schlüssel eines Rezepts, Größen, Dateinamen, erwartete Reaktionen, Beschädigungen, Archive und Presets." + }, + "recipes": { + "title": "Rezeptsammlung", + "text": "Fertige Rezepte zum Herunterladen für Uploads, Importe, Archive, E-Mails, Medien, CI und Massendateien." + }, + "guide-manifest": { + "title": "Manifest", + "text": "Jedes Feld von manifest.json und wie ein Test es liest." + }, + "guide-formats": { + "title": "Formateinstellungen", + "text": "Jede Einstellung jedes Formats mit den erlaubten Werten und dem Standardwert." + }, + "guide-frameworks": { + "title": "Test-Frameworks", + "text": "Die Dateien in pytest, Playwright, Vitest und node:test." + }, + "guide-window": { + "title": "Desktop-Anwendung", + "text": "Das Fenster, Bildschirm für Bildschirm." + } + } } } diff --git a/web/content/en/ci.html b/web/content/en/ci.html index dd4087d8..22f3e9bf 100644 --- a/web/content/en/ci.html +++ b/web/content/en/ci.html @@ -138,7 +138,7 @@

What makes a step fail, and why

A failed run prints nothing on standard output, so a log parser never reads an error as data. The - whole table is on the documentation page. + whole table is on the page of commands.

diff --git a/web/content/en/damage.html b/web/content/en/damage.html index 8fe6162e..ad5d3a13 100644 --- a/web/content/en/damage.html +++ b/web/content/en/damage.html @@ -216,7 +216,7 @@

Where to go from here

Test files in CI runs a recipe like this one in a pipeline.
  • - The documentation has every flag of tfg generate. + The page of commands has every flag of tfg generate.
  • diff --git a/web/content/en/docs.html b/web/content/en/docs.html index b422ac93..ac2ec337 100644 --- a/web/content/en/docs.html +++ b/web/content/en/docs.html @@ -1,281 +1,26 @@

    Documentation

    - Everything the tool does, arranged as the questions people actually arrive with. The - README in the repository is the full reference and always matches the - build you downloaded. + How to install tfg, make your first test files, and everything the program takes and writes: every + command and flag, every key of a recipe, every field of the manifest and every setting of every + format. The reference pages are read from the program when the site is built, so they say what the + version you download does.

    -
    -

    What commands are there?

    -

    Each one does a single thing:

    - {{ template "commandList" . }} -

    - tfg tool holds the tools for files you already have, such as checking an archive before - unpacking it. Tools describes each one. -

    -
    - -
    -

    How do I generate a single file of an exact size?

    -

    - Name the format, the size and where it goes. Sizes count in 1024s, so 2mb is - 2097152 bytes. A plain byte count works too, so --size 10485761 asks for exactly - that many. -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    The useful flags on generate:

    -
    - - - - - - - - - - - - - - - - - -
    FlagWhat it does
    --format <id>format of the files, for example txt
    --size <size>exact size of every file, such as 10mb or a plain byte count
    --size-range <a-b>a size drawn per file from a range, such as 1kb-8kb. The draw comes from the seed
    --boundary <size>three files around a limit: one byte under, the limit, one byte over
    --count <n>how many files to produce. Default 1
    --name <template>name template, for example invoice_{index:04}.txt
    --out <dir>directory to write into
    --seed <n>run seed. The same seed gives the same bytes
    --set <k>=<v>a format setting, repeatable
    --damage <name>break the files on purpose, repeatable and applied in order. Run tfg damage for the list
    --expected <outcome>accept, reject, sanitize or unspecified
    --dry-runcount and show, write nothing at all
    --jsonwrite the manifest to standard output
    -
    -
    - -
    -

    How do I make a file that is broken on purpose?

    -

    - Every other file this tool writes is correct by construction, which answers two of the three - questions an upload validator asks. --damage answers the third one - does the file - open at all. The file is produced normally and then broken, so it still has the size you asked - for. -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - Settings go after a colon. The flag repeats, and the order you write them in is the order they - are applied. tfg damage lists what this build can do and what each one takes. -

    -

    In a recipe the key is a list, of names or of settings:

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - A damaged file gets expected: reject in the manifest, with the damage recorded - beside it. Two things are refused before anything is written, because each would otherwise - put a file on disk that the manifest describes wrongly: -

    -
      -
    • a file smaller than the damage needs, because it would come out unchanged
    • -
    • - expected: accept beside a damage, because nothing could meet it. Write - sanitize if the system under test is meant to repair the file, or - unspecified if that is the question you are asking -
    • -
    -

    - A third one cannot be known in advance. If a damage runs and moves no byte, that file is - dropped rather than written - the run carries on, says which file it was, and ends with the - partial exit code. -

    -

    - Step by step, with a test that reads the manifest: how to make a corrupt file for testing. -

    +
    +

    Start here, then look things up

    + {{ template "linkCards" .Docs }}
    -
    -

    What does a recipe look like?

    -

    - A recipe is a YAML file describing a whole run. Commit it beside your tests and the fixtures stop - being binaries in your repository - anyone can rebuild them, byte for byte, from a file of a few - hundred characters. -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - Every target needs exactly one of size, size-range, boundary - or contains. Two of them is an error and so is none. An invalid recipe writes - no files at all and reports every problem at once rather than the first, each one - naming the setting it is about. -

    +
    +

    What the tool does, by topic

    + {{ template "linkCards" (.PagesOf "formats" "presets" "damage" "samples" "upload-tests" "ci" "exact-size") }}
    -
    -

    How do I declare what my system should do with a file?

    -

    Short form when the outcome is enough, long form when the reason matters:

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - The outcomes are accept, reject, sanitize and - unspecified. The reasons are a closed list so a report can group by them: - content_malformed, count_limit, dimensions_limit, - duplicate, encoding_invalid, extension_rule, - filename_invalid, filename_too_long, filename_traversal, - malware_signature, mime_mismatch, nesting_depth, - none, size_limit and size_zero. -

    -

    - A reason names the rule in play, not the verdict. That is why the same reason can - sit under either outcome - a file one byte under a limit is accept, and the rule it is - about is still size_limit. -

    -
    - -
    -

    What is in the manifest?

    -

    - It is written next to the files at the end of every run, including a run that was interrupted. One - entry per file: -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "{{ .Facts.Version }}" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - A recipe_hash is added when the run came from a recipe, and preset with - overrides when it came from a preset, so a manifest can always be traced back to what - produced it. -

    -

    - Every entry also carries target_id, the id of the target in the recipe that produced - the file, and summary.by_target counts the files each target came to. A recipe with - several targets can therefore be checked target by target without reading file names. -

    -
    - -
    -

    What is a preset?

    -

    - A ready-made set of files that answers a common testing question, so you do not have to design the - set yourself. Presets are ordinary recipes underneath, and eject prints the recipe so - you can edit it from there. Each preset has a page of its own with what it - usually finds, what is in the set and every setting it takes. -

    - {{ template "presetsList" . }} -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show tells you what the set would cost before you build it, and says outright when a - number is a placeholder of ours rather than a limit of yours. -

    -
    - -
    -

    What do the exit codes mean?

    -

    - Every ending has its own code, machine readable output goes to standard output, and a failed run - prints nothing there. The table is a frozen contract - changing what a code means requires a major - version bump. -

    - {{ template "exitCodesTable" . }} -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - A run stopped with Ctrl+C still leaves a manifest and never leaves a half written file behind, so - a cancelled job can still be cleaned up by the next one. -

    -

    - Ready workflows for GitHub Actions and GitLab CI: how to generate test files in a CI pipeline. -

    -
    - -
    -

    Is there a desktop window?

    -

    - Yes, the same engine with a window on it, for the testing that is not scripted. It is not a cut - down version: a test compares the two interfaces capability by capability, and anything only one of - them can do has to be declared and justified rather than quietly drifting apart. -

    +
    +

    Still stuck?

    - The screens are one batch, presets, several batches at once, and about. It shows what a run would - cost before writing anything, reports progress while it runs, and can be cancelled part way without - leaving a half written file behind. It does not open a recipe file yet - recipes are a command line - thing for now, and the window builds its batches in the form. + tfg <command> --help says what a command takes, in the terminal. Every refusal names + the setting it is about, why, and a value that would work. If something does not behave the way a page + here says, open an issue. That is a bug in the page or in the program.

    diff --git a/web/content/en/guide-commands.html b/web/content/en/guide-commands.html new file mode 100644 index 00000000..d053ddec --- /dev/null +++ b/web/content/en/guide-commands.html @@ -0,0 +1,71 @@ +

    Commands

    +

    + Every command of tfg with every flag it takes. This page is read from the program's own + help when the page is built, so it says what the program says: tfg <command> --help + prints the same in your terminal. +

    + +
    + + + + {{- range .Facts.Docs.Commands }} + + {{- end }} + +
    CommandWhat it does
    tfg {{ .Name }}{{ ascii .Summary }}
    +
    +

    + A flag is written with two dashes, as --count 10, or with one. A flag that takes no value + is on when it is there. Every exit code is at the end of this page. +

    + +{{- range .Facts.Docs.Commands }} + +
    +

    tfg {{ .Name }}

    +

    {{ ascii .Summary }}

    + {{- range .About }} +

    {{ ascii . }}

    + {{- end }} + {{- if .Usage }} +
    {{ range $i, $u := .Usage }}{{ if $i }}
    +{{ end }}{{ ascii $u }}{{ end }}
    + {{- end }} + {{- range .Notes }} +

    {{ ascii . }}

    + {{- end }} + {{- if .Flags }} +
    + + + + {{- range .Flags }} + + + + + + {{- end }} + +
    FlagDefaultWhat it does
    {{ if eq (len .Name) 1 }}-{{ else }}--{{ end }}{{ .Name }}{{ with .Takes }} {{ . }}{{ end }}{{ with .Default }}{{ ascii . }}{{ end }}{{ ascii .Text }}
    +
    + {{- end }} +
    +{{- end }} + +
    +

    Exit codes

    +

    + Every ending has a code of its own, so a script or a pipeline can tell them apart. Output meant for + a program goes to standard output, and a run that fails prints nothing there. The meaning of a code + never changes within a major version. +

    + {{ template "exitCodesTable" . }} +

    + A run stopped with Ctrl+C still leaves a manifest and never a half written file, so the next run + can clean up after it. In PowerShell, end a script with exit $LASTEXITCODE, because a + .ps1 file does not pass the code of a program on by itself. More in + Test files in CI. +

    +
    diff --git a/web/content/en/guide-formats.html b/web/content/en/guide-formats.html new file mode 100644 index 00000000..d8d27c20 --- /dev/null +++ b/web/content/en/guide-formats.html @@ -0,0 +1,50 @@ +

    Format settings

    +

    + Every setting each format takes, with the values it accepts, its default and what it changes in the + file. The list is read from the program when this page is built, in the program's own words: + tfg formats <id> prints the same for one format. +

    + +
    +

    How to give a setting

    +

    On the command line, --set takes one setting and repeats. In a recipe, the settings go under properties:

    +
    tfg generate --format pdf --size 1mb --set pages=20 --set page_size=letter --out ./pdf
    +
    targets:
    +  - id: report
    +    format: pdf
    +    size: 1mb
    +    properties:
    +      pages: 20
    +      page_size: letter
    +

    + A setting left out takes its default. A value outside what the setting accepts is refused before + anything is written, with the values that would work. Some settings also limit the smallest size a + file can be, and a size below it is refused with the size that would work. The list of formats + themselves, with the smallest file of each, is on Formats. +

    +

    + {{ range $i, $f := .FormatSettingsList }}{{ if $i }} {{ end }}{{ $f.ID }}{{ end }} +

    +
    + +{{- range .FormatSettingsList }} + +
    +

    {{ .ID }} {{ .Name }}

    +
    + + + + {{- range .Settings }} + + + + + + + {{- end }} + +
    SettingAcceptsDefaultWhat it does
    {{ .Name }}{{ .Takes }}{{ with .Default }}{{ . }}{{ end }}{{ .Detail }}
    +
    +
    +{{- end }} diff --git a/web/content/en/guide-frameworks.html b/web/content/en/guide-frameworks.html new file mode 100644 index 00000000..675ff2a2 --- /dev/null +++ b/web/content/en/guide-frameworks.html @@ -0,0 +1,148 @@ +

    Test frameworks

    +

    + Two packages bring the files into your tests: testing-files-generator on PyPI for pytest + and unittest, and the package of the same name on npm for Playwright, Vitest and + node:test. Each gives you one test for each file of a set, named by what the file should + meet, and fails a test with a sentence that says what went wrong. +

    + +
    +

    How it works

    +

    + You choose a set, usually a preset. The package plans it and gives you its files. Each test hands + its file to your system and ends with one line saying what your system did. A file with no right + answer is skipped, never passed. tfg comes inside both packages, works offline and never connects + to the network. +

    +
    + +
    +

    pytest

    +
    pip install testing-files-generator
    +

    + pytest finds the plugin on its own. Python 3.10 or later. This test sends every file of the + upload-validation preset to an upload endpoint with + requests, around a limit of 2 MB: +

    +
    # tests/test_upload.py
    +import pytest
    +import requests
    +from testing_files_generator import file_set
    +
    +uploads = file_set(preset="upload-validation", options={"limit": "2mb", "bulk": 0})
    +
    +
    +@pytest.mark.parametrize("file", uploads.params())
    +def test_upload(file):
    +    with open(file.path(), "rb") as body:
    +        response = requests.post("http://localhost:3000/upload", files={"file": (file.send_as, body)}, timeout=30)
    +    assert response.status_code < 500, "a server error is not a refusal"
    +    file.check("accept" if response.ok else "reject")
    +

    Each test is named by its file and what the file expects. Listing them writes no file:

    +
    pytest --collect-only -q
    +
    tests/test_upload.py::test_upload[2mb_under_1b.jpg - expected accept]
    +tests/test_upload.py::test_upload[2mb_at_limit.jpg - expected accept]
    +tests/test_upload.py::test_upload[2mb_over_1b.jpg - expected reject (size_limit)]
    +tests/test_upload.py::test_upload[pdf_as_jpg.jpg - expected reject (mime_mismatch)]
    +...
    +

    + Every test carries its outcome and its group as markers, so pytest -m reject or + pytest -m size-limit runs part of the set. Without pytest, the same set works in + unittest or any runner that makes tests in a loop. +

    +
    + +
    +

    Playwright

    +
    npm install --save-dev testing-files-generator
    +

    This spec uploads every file through the form, the way a person does:

    +
    // tests/upload.spec.ts
    +import { test, expect } from '@playwright/test';
    +import { fileSet } from 'testing-files-generator';
    +
    +const uploads = fileSet({ preset: 'upload-validation', options: { limit: '2mb', bulk: 0 } });
    +
    +for (const file of uploads.files) {
    +  test(file.title, file.details, async ({ page }) => {
    +    test.skip(file.unspecified, file.whyUnspecified);
    +    await page.goto('/upload');
    +    await page.getByLabel('File').setInputFiles(await file.path());
    +    await page.getByRole('button', { name: 'Upload' }).click();
    +    const status = page.getByRole('status');
    +    await expect(status).toHaveText(/Uploaded|Refused/);
    +    file.check((await status.textContent())?.includes('Uploaded') ? 'accept' : 'reject');
    +  });
    +}
    +

    + Only the lines that upload and read the answer are about your app. Change them to however your + app takes a file. Wait for an answer your app gives on purpose, as Uploaded or + Refused here, so a page that shows an error fails the test rather than passing as a + refusal. npx playwright test --grep @reject runs part of the set. +

    +
    + +
    +

    Vitest and node:test

    +

    + The package imports nothing from Playwright, so any runner that declares tests in a loop works. + With Vitest: +

    +
    import { test, expect } from 'vitest';
    +import { openAsBlob } from 'node:fs';
    +import { fileSet } from 'testing-files-generator';
    +
    +const uploads = fileSet({ preset: 'upload-validation', options: { limit: '2mb', bulk: 0 } });
    +
    +for (const file of uploads.files) {
    +  test.skipIf(file.unspecified)(file.title, async () => {
    +    const body = new FormData();
    +    body.append('file', await openAsBlob(await file.path()), file.sendAs);
    +    const response = await fetch('http://localhost:3000/upload', { method: 'POST', body });
    +    expect(response.status, 'a server error is not a refusal').toBeLessThan(500);
    +    file.check(response.ok ? 'accept' : 'reject');
    +  });
    +}
    +

    + With the runner built into Node, node --test, the loop is the same, with + test(file.title, { skip: file.unspecified && file.whyUnspecified }, ...). +

    +
    + +
    +

    Telling the set what your system did

    +

    + check takes accept, reject or sanitize and fails + the test when the file expected something else. When your system says why it turned a file away, + pass the reason as well, and a file turned away for the wrong rule fails too. In Python: +

    +
    file.check({"outcome": "reject", "reason": response.json().get("reason")})
    +

    + A server error is not a refusal, so check the status before check, as the examples do. + A file sent under another name, such as ../climbed_out.jpg, gives that name in + send_as, or sendAs in Node, and the examples upload it under that name. +

    +
    + +
    +

    Your own set

    +

    + Any preset works in place of upload-validation, with its settings in + options. For a set of your own, write a recipe and name it: +

    +
    uploads = file_set(recipe="tests/fixtures.yaml")
    +
    const uploads = fileSet({ recipe: path.join(__dirname, 'fixtures.yaml') });
    +

    + Recipes says how to write one, and the recipe + gallery has ready ones to start from. +

    +
    + +
    +

    Everything else

    +

    + Each package has a full guide of its own, with where the files are kept, CI, every option and what + to do when something goes wrong: + testing-files-generator on PyPI and + testing-files-generator on npm. +

    +
    diff --git a/web/content/en/guide-install.html b/web/content/en/guide-install.html new file mode 100644 index 00000000..f100883d --- /dev/null +++ b/web/content/en/guide-install.html @@ -0,0 +1,140 @@ +

    Install

    +

    + There are two programs. tfg is the command line, for scripts and pipelines. + tfg-gui is the desktop window, for testing by hand. Both make the same files from the + same settings. Pick the way of installing that fits where you will run them. +

    + +
    +

    The short answer

    +

    + Download the archive for your system from the releases page, unpack it and run + tfg version. Everything runs on your machine, and the program never connects to the + internet. +

    +
    + +
    +

    Download a binary

    +

    + Take the archive for your system from the releases page, unpack it anywhere and run the program + inside. Nothing else is needed. These are the systems each program is built for: +

    + {{ template "downloadsTable" . }} +

    + The archives are named after the program, the version, the system and the processor, such as + tfg_{{ .Facts.Released }}_linux_amd64.tar.gz or + tfg-gui_{{ .Facts.Released }}_windows_amd64.zip. On Windows x64 the release also has an + installer, tfg-setup_{{ .Facts.Released }}_windows_amd64.msi. +

    +

    + The Windows and macOS programs are signed, so they start without a warning about an unknown + developer. The Linux ones are not, because desktop Linux has nothing to sign them with. +

    + {{ template "downloadCta" . }} +
    + +
    +

    Check that the archive is the one this project published

    +

    + Every release has a verify-SHA256SUMS.txt with the checksum of every archive. A + matching checksum says the archive arrived whole. With the GitHub command line installed, the + attestation also says the release workflow of this project made it. +

    +
    tfg_version={{ .Facts.Released }}
    +archive=tfg_${tfg_version}_linux_amd64.tar.gz
    +url=https://github.com/donislawdev/TestingFilesGenerator/releases/download/v$tfg_version
    +curl -fsSLO "$url/$archive"
    +curl -fsSLO "$url/verify-SHA256SUMS.txt"
    +grep " $archive\$" verify-SHA256SUMS.txt | shasum -a 256 -c
    +gh attestation verify "$archive" --repo donislawdev/TestingFilesGenerator --predicate-type https://spdx.dev/Document/v2.3
    +

    + Without shasum, tfg tool checksum does the same on any system once you + have one copy of tfg you trust: tfg tool checksum <archive> --expected <sum>. +

    +
    + +
    +

    Run it from Docker

    +

    + The command line also comes as an image for Linux, on x64 and Arm. It holds the program from the + release archive and nothing else, and it runs with no network. Name the version rather than + latest, so the same recipe gives the same files next month too. +

    +
    docker run --rm --network none -v "${PWD}:/work" ghcr.io/donislawdev/tfg:{{ .Facts.Released }} generate --format pdf --size 1mb
    +

    + The files land in the current directory. On Linux add --user "$(id -u):$(id -g)", so + the image may write there and the files belong to you. With no directory mounted, the run stops + with exit code 5 rather than writing files that disappear with the container. +

    +
    + +
    +

    Install it with npm, for tests in Node

    +

    + The testing-files-generator package gives Playwright, Vitest and + node:test a generated set of files and what your system should do with each, and + installs the tfg of the same release for your system. It comes for Windows and Linux on x64 and + Arm, and for macOS on Apple silicon. +

    +
    npm install --save-dev testing-files-generator
    +npx tfg version
    +

    How to use it in a test: Test frameworks.

    +
    + +
    +

    Install it with pip, for tests in Python

    +

    + The testing-files-generator package gives pytest and unittest a generated set of + files and what your system should do with each, and installs the tfg of the same release for + your system. pytest finds its plugin on its own. uv installs it as well. +

    +
    pip install testing-files-generator
    +tfg version
    +

    + If tfg is not found, the folder pip puts programs in is not on your + PATH, and python -m testing_files_generator version runs the same tfg. +

    +
    + +
    +

    Install it with Go

    +

    With Go installed, this builds the command line and puts it in your Go bin folder:

    +
    go install -tags noasm github.com/donislawdev/TestingFilesGenerator/cmd/tfg@latest
    +

    + The tag is not optional. It turns off a path of the AVIF encoder that reads past the end of a + buffer on some picture sizes. Built without it, the program does not compile, and says why. The + files are the same either way. +

    +
    + +
    +

    Build it from source

    +

    It needs Go and nothing else:

    +
    git clone https://github.com/donislawdev/TestingFilesGenerator
    +cd TestingFilesGenerator
    +go build -tags "$(cat .github/build-tags)" ./cmd/tfg
    +

    + The window is a second program, go build -tags "$(cat .github/build-tags)" ./cmd/tfg-gui. + It draws through OpenGL and reaches it through C, so it needs a C compiler on the system it is + built for. Built without one, it still compiles, and says on start that it has no window and + that everything is on the command line. +

    +
    + +
    +

    When the window does not open

    +

    + The window needs OpenGL 2.1 to draw. On Windows the archive carries a software renderer, in an + opengl folder next to tfg-gui.exe, for machines whose graphics driver + offers none: a virtual machine without 3D acceleration, a remote desktop, a server. The window + uses it by itself when the driver refuses, and says so on its About screen. Keep the folder next + to the program. +

    +

    + tfg-gui --software-gl uses the software renderer on any Windows machine, which shows + the window the way a machine without a driver sees it. Linux and macOS have what the window + needs, so there the flag changes nothing. The command line needs no graphics at all and does + everything the window does. +

    +
    diff --git a/web/content/en/guide-manifest.html b/web/content/en/guide-manifest.html new file mode 100644 index 00000000..8819344b --- /dev/null +++ b/web/content/en/guide-manifest.html @@ -0,0 +1,112 @@ +

    Manifest

    +

    + Every run writes manifest.json beside its files. It lists every file with its size, its + SHA-256 and what your system should do with it, so a test reads the expectation instead of hard + coding it. It is written even when a run is stopped part way. +

    + +
    +

    What a manifest looks like

    +

    This is the manifest of tfg generate --format png --size 2mb --out ./out, shortened:

    +
    {
    +  "manifest_version": "1.0",
    +  "tool": { "name": "testing-files-generator", "version": "{{ .Facts.Version }}" },
    +  "run": {
    +    "id": "run_b359aa8d94",
    +    "seed": 0,
    +    "command": "tfg generate --format png --size 2mb --out ./out",
    +    "platform": { "os": "windows", "arch": "amd64" },
    +    "complete": true
    +  },
    +  "summary": {
    +    "file_count": 1,
    +    "total_bytes": 2097152,
    +    "by_format": { "png": 1 },
    +    "by_expected": { "unspecified": 1 }
    +  },
    +  "files": [
    +    {
    +      "path": "files_0001.png",
    +      "bytes": 2097152,
    +      "format": "png",
    +      "fidelity": "full",
    +      "determinism": "byte",
    +      "seed": "8dc2d18c",
    +      "hashes": { "sha256": "1a1f7c..." },
    +      "properties": { "width": 640, "height": 480 },
    +      "expected": {
    +        "outcome": "unspecified",
    +        "detail": "No expectation was declared for this file.",
    +        "confidence": "policy_dependent"
    +      }
    +    }
    +  ]
    +}
    +
    + +
    +

    How a test reads it

    +

    + Go through files, give each file to your system, and compare what it did with + expected.outcome. When send_as is there, give the file under that name. A + sketch in Python, with your own upload in place of upload: +

    +
    import json, pathlib
    +
    +folder = pathlib.Path("fixtures")
    +manifest = json.loads((folder / "manifest.json").read_text(encoding="utf-8"))
    +for f in manifest["files"]:
    +    if f["expected"]["outcome"] == "unspecified":
    +        continue
    +    result = upload(folder / f["path"], name=f.get("send_as", f["name"]))
    +    assert result == f["expected"]["outcome"], f["path"]
    +

    + The packages for pytest and Node do this for you: Test frameworks. + An outcome of unspecified means the right reaction depends on how your system is set up. + policy_options lists the answers left open, for a test that settles them by your policy. +

    +
    + +
    +

    Every field

    +

    + Every field a manifest can carry, read from the program when this page is built. [] + stands for each entry of a list, and * for each key of an object whose keys are yours, + such as the names of the flags in run.overrides. A field marked as present only in some + runs is left out of the others rather than written empty. +

    +
    + + + + {{- range .ManifestRows }} + + {{- end }} + +
    FieldWhat it holds
    {{ .Key }}{{ .Text }}
    +
    +
    + +
    +

    What else is written beside it

    +

    + When the files of a run have a purpose, from a preset or from purpose in a recipe, a + second file is written beside the manifest, manifest.instructions.md. It says in words + what each file is and why it is in the set, for the person running the test by hand. + verify and cleanup know about it. +

    +

    + tfg verify manifest.json checks that every file is still there and still has its SHA-256. + tfg cleanup manifest.json --yes removes exactly the files the manifest lists, and + nothing else, so it is safe in a folder that holds other things too. +

    +
    + +
    +

    Can I rely on the format?

    +

    + Yes. manifest_version is 1.0, and the format grows only by adding fields. + A field never changes its meaning within a version, so a reader written today keeps working if it + ignores the fields it does not know. +

    +
    diff --git a/web/content/en/guide-recipes.html b/web/content/en/guide-recipes.html new file mode 100644 index 00000000..7ded43ca --- /dev/null +++ b/web/content/en/guide-recipes.html @@ -0,0 +1,234 @@ +

    Recipes

    +

    + A recipe is a YAML file that describes a whole run: which files, how many, how large, and what your + system should do with each. Commit it beside your tests and the test files stop being binaries in + your repository. Anyone rebuilds them from the recipe, byte for byte. +

    + +
    +

    What a recipe looks like

    +
    # fixtures.yaml
    +version: 1
    +seed: 7741
    +
    +defaults:
    +  label: true
    +
    +targets:
    +  - id: invoices
    +    format: pdf
    +    count: 25
    +    size: 300kb
    +    name: invoice_{index:04}.pdf
    +    properties:
    +      pages: 3
    +      page_size: a4
    +    expected: accept
    +
    +  - id: over_the_limit
    +    format: png
    +    count: 2
    +    size: 12mb
    +    expected:
    +      outcome: reject
    +      reason: size_limit
    +
    +  - id: bundle
    +    format: zip
    +    contains:
    +      - format: txt
    +        count: 200
    +        size: 4kb
    +
    +output:
    +  dir: ./fixtures
    +  manifest: manifest.json
    +
    tfg validate fixtures.yaml
    +tfg generate fixtures.yaml
    +

    + Every recipe has a version and a list of targets. A target is one kind of + file: it needs an id, a format and exactly one of size, + size-range, boundary or contains. Two of them is an error, + and so is none. +

    +

    + An invalid recipe writes no files at all. validate and + generate report every problem at once, each naming the key it is about, so one run + shows everything to fix. +

    +
    + +
    +

    Keys of the whole recipe

    +

    + Every key a recipe accepts is listed here, read from the program when this page is built. A key + marked as not built yet is refused with a message saying so, never ignored. +

    +
    + + + + {{- range .RecipeKeyRows }}{{ if not .Target }} + + {{- end }}{{ end }} + +
    KeyWhat it does
    {{ .Key }}{{ .Text }}
    +
    +
    + +
    +

    Keys of a target

    +
    + + + + {{- range .RecipeKeyRows }}{{ if .Target }} + + {{- end }}{{ end }} + +
    KeyWhat it does
    {{ .Key }}{{ .Text }}
    +
    +
    + +
    +

    How to write a size

    +

    + A size is a number with a unit: b, kb, mb, gb + or tb. Units count in 1024s, the way a file manager does, so 10mb is + 10 485 760 bytes. kib, mib, gib and tib mean the + same and say so. A fraction works, as in 1.5mb, and so does a plain byte count, as in + 10485761. +

    +
      +
    • size: 300kb - every file of the target is exactly that large
    • +
    • size-range: 1kb-8kb - each file gets a size from the range, drawn from the seed
    • +
    • boundary: 5mb - three files: one byte under, the limit itself, one byte over
    • +
    • size: smallest - a picture as small as it can be at the width and height you set
    • +
    +

    + When a format cannot reach a size, the run is refused before anything is written, with the + smallest size the format can make and what to change. A size is never rounded quietly. +

    +
    + +
    +

    How to name the files

    +

    + name is a template. {index:04} is the number of the file, padded to four + digits, and it is the only placeholder there is. Without a template a file is named after its target, + as invoices_0001.pdf. +

    +
    name: invoice_{index:04}.pdf
    +

    + A name no disk stores, such as ../climbed_out.jpg, goes in send-as. The file + keeps an ordinary name on disk, and the manifest carries the other one in send_as, for + the test to upload it under. +

    +
    + +
    +

    How to declare what your system should do

    +

    Short form, when the outcome is enough. Long form, when the reason matters:

    +
    expected: accept
    +
    expected:
    +  outcome: reject
    +  reason: size_limit
    +

    + The outcomes are {{ range $i, $o := .Facts.Docs.Outcomes }}{{ if $i }}, {{ end }}{{ $o }}{{ end }}. + The reasons are a closed list, so a report can group by them: + {{ range $i, $r := .Facts.Docs.Reasons }}{{ if $i }}, {{ end }}{{ $r }}{{ end }}. +

    +

    + A reason names the rule in play, not the verdict. That is why one reason can sit + under either outcome: a file one byte under a limit is accept, and the rule it is about + is still size_limit. Where the right reaction depends on how your system is set up, the + manifest says unspecified and explains why, rather than guessing. +

    +
    + +
    +

    How to break files on purpose

    +

    + damage is a list, applied in the order written. Each entry is a name, or a + type with its settings. The file still has the size you asked for: +

    +
    targets:
    +  - id: broken
    +    format: png
    +    count: 5
    +    size: 2mb
    +    damage:
    +      - zero-head
    +      - type: truncate
    +        missing: 30
    +    expected:
    +      outcome: reject
    +      reason: content_malformed
    +

    + tfg damage lists the damages and what each takes. Asking for accept beside a + damage that breaks the rules of the format is refused, because nothing could meet it. More in + Corrupt test files. +

    +
    + +
    +

    How to fill an archive

    +

    + contains lists what goes inside a ZIP or a TAR.GZ. Each entry has a format, a count and + a size, and every file inside is a real file of its format. The archive is as large as what it + holds: +

    +
    targets:
    +  - id: bundle
    +    format: zip
    +    contains:
    +      - format: pdf
    +        count: 3
    +        size: 200kb
    +      - format: csv
    +        count: 10
    +        size: 8kb
    +

    + The settings of the archive itself, such as compression, depth or a password, are in + Format settings. +

    +
    + +
    +

    How to build on a preset

    +

    + A recipe can start from the set of a preset and add its own targets after it. with gives + the preset its settings, written the way its flags take them: +

    +
    version: 1
    +seed: 7
    +extends: preset:size-boundaries
    +with:
    +  limit: 5mb
    +  format: png
    +targets:
    +  - id: our-legacy-format
    +    format: tiff
    +    count: 1
    +    size: 3mb
    +

    + This makes the same files as tfg preset eject size-boundaries --limit 5mb --format png + with the extra target typed under it. A target whose id the preset already uses is + refused, never quietly replaced. The manifest names the preset, and lists the settings you left to + its defaults. +

    +
    + +
    +

    How to check a recipe before a commit

    +
    tfg validate fixtures.yaml
    +tfg recipe fmt fixtures.yaml --check
    +

    + validate says whether the recipe makes sense and what it would make, and writes nothing. + recipe fmt --check says whether the file is laid out in its settled shape, and + recipe fmt -w lays it out, comments kept. Run both in a pre-commit hook. +

    +

    + Ready recipes to download and change are in the recipe gallery. +

    +
    diff --git a/web/content/en/guide-start.html b/web/content/en/guide-start.html new file mode 100644 index 00000000..c3902a09 --- /dev/null +++ b/web/content/en/guide-start.html @@ -0,0 +1,117 @@ +

    Getting started

    +

    + Five minutes from an installed tfg to a set of test files your tests can rely on. Every + command here runs as it is, on Windows, macOS and Linux. If you have not installed it yet, start + with Install. +

    + +
      +
    1. +

      Make one file of an exact size

      +

      Name the format, the size and the folder. This makes one PNG of exactly two megabytes:

      +
      tfg generate --format png --size 2mb --out ./out
      +
      1 file in 1 target, 2 097 152 B total
      +

      + Sizes count in 1024s, the way a file manager does, so 2mb is 2 097 152 bytes. A + plain byte count works too. The PNG opens in any picture viewer, and beside it is + manifest.json, the record of what the run made and how your system should react + to each file. +

      +
    2. +
    3. +

      Make many files at once

      +

      + Ten thousand log files, each between one and eight kilobytes. The sizes are drawn from the seed, + so the same command gives the same set tomorrow and on any other machine: +

      +
      tfg generate --format log --size-range 1kb-8kb --count 10000 --out ./logs
      +

      + Give each run its own folder. The manifest is the only record of what a run + wrote, so a second run into a folder that holds one is refused rather than written over it. Add + --number-if-taken to put the second run beside the first instead. +

      +
    4. +
    5. +

      Check the files, then remove them

      +

      + verify says whether every file is still there and still the same. + cleanup removes the files the manifest lists and nothing else. Without + --yes it only says what it would remove: +

      +
      tfg verify ./out/manifest.json
      +tfg cleanup ./out/manifest.json
      +tfg cleanup ./out/manifest.json --yes
      +
      out matches ./out/manifest.json: 1 file checked
      +1 file would be removed from out:
      +  remove files_0001.png
      +Nothing was removed. Run the same command with --yes to remove them.
      +1 file removed from out
      +
    6. +
    7. +

      Say what your system should do with the files

      +

      + A test file is only half a test. The other half is what should happen to it. Write it on the + command line and the manifest carries it beside every file: +

      +
      tfg generate --format pdf --size 12mb --expected reject --expected-reason size_limit --out ./too-big
      +

      + For a size limit, the size-boundaries preset makes the whole set at once: files + just under the limit, at it and just over it, each with its expected outcome: +

      +
      tfg generate --preset size-boundaries --limit 10mb --format pdf --out ./limit
      +
    8. +
    9. +

      Make a file that is broken on purpose

      +

      + A damaged file still has the size you asked for, and the manifest expects your system to turn + it away. tfg damage lists the damages this build has: +

      +
      tfg generate --format png --size 2mb --damage zero-head --out ./broken
      +
    10. +
    11. +

      Turn the run into a recipe

      +

      + Once the set is right, write it down. A recipe is a short YAML file you commit beside your + tests, so the files never have to be committed: anyone rebuilds them, byte for byte. +

      +
      # fixtures.yaml
      +version: 1
      +seed: 7741
      +
      +targets:
      +  - id: invoices
      +    format: pdf
      +    count: 25
      +    size: 300kb
      +    name: invoice_{index:04}.pdf
      +    expected: accept
      +
      +  - id: too_big
      +    format: pdf
      +    size: 12mb
      +    expected:
      +      outcome: reject
      +      reason: size_limit
      +
      +output:
      +  dir: ./fixtures
      +
      tfg validate fixtures.yaml
      +tfg generate fixtures.yaml
      +

      + validate checks the recipe and writes nothing. Every key is in + the recipe reference, and the recipe gallery + has ready recipes to start from. +

      +
    12. +
    + +
    +

    Where to go next

    +
      +
    • Test files in CI - a GitHub Actions workflow and a GitLab job that build the set in the pipeline
    • +
    • Test frameworks - the set inside pytest, Playwright, Vitest and node:test
    • +
    • The manifest - every field a test can read
    • +
    • Commands - every flag of every command
    • +
    • Presets - ready sets for common testing questions
    • +
    +
    diff --git a/web/content/en/guide-window.html b/web/content/en/guide-window.html new file mode 100644 index 00000000..13c0ccd5 --- /dev/null +++ b/web/content/en/guide-window.html @@ -0,0 +1,95 @@ +

    Desktop app

    +

    + tfg-gui is the same program with a window on it, for the testing that is not scripted. + It makes the same files from the same settings as the command line, and a test compares the two + screen by screen, so nothing one of them can do quietly goes missing from the other. +

    + +
    +

    Before anything is written

    +

    + Every screen shows what a run would make before you start it: how many files, how many bytes, which + formats and where they go. Preview lists the files without writing any. A run shows its progress + and can be cancelled part way without leaving a half written file behind. +

    +
    + +
    +

    Single batch

    +

    + Files of one format: choose the format, how the size is given, the size and how many files. The + settings of the format open under the form, and a box beside every field says what it does. A value + the format cannot take is marked under its field, with the value that would work. +

    +
    + The Single batch screen: format, size, how many files, damage, batch name and the output folder +
    +
    + +
    +

    Presets

    +

    + A ready set that answers one question about the system you test, such as whether a size limit is + enforced exactly where it is declared. The screen says what each preset typically finds, takes its + settings, and shows the cost of the set before it is made. + Presets describes every one. +

    +
    + The Presets screen with a preset chosen, what it typically finds, its settings and the output folder +
    +
    + +
    +

    Several batches

    +

    + Batches of different formats and sizes made together in one run, with one manifest. A batch can be + duplicated and changed, can carry notes for the manifest, and the whole run can start from a preset, + whose files come first. +

    +
    + The Several batches screen with one batch, the choice to build on a preset, and the output settings +
    +
    + +
    +

    Tools

    +

    + The tools for files you already have, with the same settings as tfg tool: a checksum + compared with the one you were given, checksums for a whole folder, and whether an archive is safe to + unpack. A file or a folder dropped on the screen goes into the box of the chosen tool. + Tools says what each one finds. +

    +
    + The Tools screen with a checksum worked out and matching the one that was expected +
    +
    + +
    +

    Preferences and About

    +

    + Preferences sets the language of the window, how much memory a run may take, and shows what the + window keeps between runs and where. Forget clears what it keeps. Only the window changes language. + The files, recipes, manifests and the command line stay in English. About shows the version, how to + use the window in three steps, and the licence. +

    +
    + +
    +

    The output folder

    +

    + A folder dropped on the window becomes the output folder. A run into a folder that holds an earlier + run is added beside it: every name of the run, its manifest too, gets a number, as + files-2_0001.pdf and manifest-2.json, and nothing already there changes. The + switch for this, Add beside earlier runs, stays on unless you turn it off. With it off, such a run is + refused, the same as on the command line without --number-if-taken. +

    +
    + +
    +

    What it does not do yet

    +

    + The window does not open a recipe file. Recipes are a command line thing for now, and the window + builds its batches in the form. If the window does not open at all, see + when the window does not open. +

    +
    diff --git a/web/content/en/recipes.html b/web/content/en/recipes.html new file mode 100644 index 00000000..ee09e3f1 --- /dev/null +++ b/web/content/en/recipes.html @@ -0,0 +1,69 @@ +

    Recipe gallery

    +

    + Ready recipes for test sets people build again and again. Download one, run it, and change it to fit + your system. Each is a short YAML file with a comment on every part, and each writes into a folder of + its own name, so several can run one after another. +

    + +
    +

    How to use one

    +

    + Download the file, then run tfg generate image-upload.yaml. The files and the manifest + land in ./image-upload. Change a limit, a size or a count in the file, and + tfg validate image-upload.yaml checks it before anything is written. +

    +
    + + + +
    +

    Every preset as a recipe

    +

    + A preset is a recipe with a name. These are the recipes the presets stand for, as + tfg preset eject prints them with their default settings. They name no output folder, so + give them one with --out. Each preset has a page of its own with + what it finds and every setting it takes. +

    +
    + + + + {{- range .PresetRecipes }} + + + + + + + {{- end }} + +
    PresetThe question it answersFilesBytes
    {{ .File }}
    {{ .Title }}
    {{ .Text }}{{ .Files }}{{ .Bytes }}
    +
    +
    tfg generate size-boundaries.yaml --out ./size-boundaries
    +
    + +
    +

    Write your own

    +

    + Every key a recipe takes is in the recipe reference, and every setting of + every format in Format settings. A recipe can also start from a + preset with extends, as the image, document and media recipes here do, and add its own + files after the set of the preset. +

    +
    diff --git a/web/content/en/site.json b/web/content/en/site.json index 4063cf6e..f46a4d2a 100644 --- a/web/content/en/site.json +++ b/web/content/en/site.json @@ -82,6 +82,87 @@ "description": "Test cases for a file upload: the size limit, empty and corrupt files, the wrong type, unexpected file names and archives, each with the file that tests it.", "parent": "use-cases" }, + { + "key": "guide-install", + "slug": "docs/install", + "nav": "Install", + "title": "Install Testing Files Generator on Windows, macOS, Linux or Docker", + "description": "Download the command line tool and the desktop window, check that the archive is the one this project published, or run it from Docker, npm, pip or Go.", + "parent": "docs", + "untranslated": true + }, + { + "key": "guide-start", + "slug": "docs/getting-started", + "nav": "Getting started", + "title": "Getting Started - Your First Test Files in Five Minutes", + "description": "Make one file of an exact size, then ten thousand, check them against the manifest, remove them, and turn the run into a recipe you can commit.", + "parent": "docs", + "untranslated": true + }, + { + "key": "guide-commands", + "slug": "docs/commands", + "nav": "Commands", + "title": "Command Reference - Every tfg Command, Flag and Exit Code", + "description": "Every command of the tfg command line with every flag it takes, its default and what it does, read from the program's own help, and every exit code.", + "parent": "docs", + "untranslated": true + }, + { + "key": "guide-recipes", + "slug": "docs/recipes", + "nav": "Writing recipes", + "title": "Recipe Reference - Every Key of a Test File Recipe in YAML", + "description": "How to write a recipe: every key it accepts, the ways to give a size, name templates, expected outcomes and reasons, damage, archive contents and presets.", + "parent": "docs", + "untranslated": true + }, + { + "key": "recipes", + "slug": "recipes", + "nav": "Recipe gallery", + "title": "Test File Recipes to Download - Ready YAML for Uploads, Imports and CI", + "description": "Ready recipes for common test sets: image and document uploads, table imports, archives, email, media, CI and bulk files. Download one, run it, change it.", + "parent": "docs", + "untranslated": true + }, + { + "key": "guide-manifest", + "slug": "docs/manifest", + "nav": "Manifest", + "title": "Manifest Reference - What manifest.json Says About Each Test File", + "description": "Every field of the manifest written beside the files: the run, the summary, and each file with its hash, its settings and how your system should react to it.", + "parent": "docs", + "untranslated": true + }, + { + "key": "guide-formats", + "slug": "docs/format-settings", + "nav": "Format settings", + "title": "Format Settings - Every Option of Every Test File Format", + "description": "Every setting each format takes, such as pages, picture size, delimiter or encoding, with the values it accepts, its default and what it changes in the file.", + "parent": "docs", + "untranslated": true + }, + { + "key": "guide-frameworks", + "slug": "docs/test-frameworks", + "nav": "Test frameworks", + "title": "Test Files in pytest, Playwright, Vitest and node:test", + "description": "Use generated test files inside your tests: the pytest plugin and the npm package for Playwright, Vitest and node:test, with what each file should be met with.", + "parent": "docs", + "untranslated": true + }, + { + "key": "guide-window", + "slug": "docs/desktop-app", + "nav": "Desktop app", + "title": "Desktop App - Generate Test Files Without the Command Line", + "description": "The window of Testing Files Generator screen by screen: one batch, presets, several batches, tools and preferences, with what each of them does.", + "parent": "docs", + "untranslated": true + }, { "key": "tools", "slug": "tools", @@ -138,7 +219,8 @@ "colSha256": "SHA-256", "colExpected": "Expected", "colTool": "Tool", - "colQuestion": "What it answers" + "colQuestion": "What it answers", + "docsMenuLabel": "Documentation pages" }, "endings": { "0": "Everything worked.", @@ -386,5 +468,148 @@ "checksum": "Is this file the one it claims to be?", "checksum-check": "Is every file still what its checksum file says?", "checksum-write": "How will I know later that none of these files changed?" + }, + "docs": { + "recipeKeys": { + "allow_nondeterministic": "Consent to formats whose bytes differ from run to run. Every format of this build repeats to the byte, so `true` is refused for now and the line can be left out.", + "defaults": "Settings every target takes unless it says otherwise.", + "defaults.fill": "How the content of the files is made. Not built yet: a recipe with this key is refused, and the content always comes from the seed.", + "defaults.label": "Whether each file carries a short label saying which run made it. `true` unless you say otherwise. The label is written so that the file stays valid.", + "engine": "The version of tfg the recipe needs. Not built yet: a recipe with this key is refused, and the manifest records the version that ran.", + "extends": "A preset to build on, written as `preset:size-boundaries`. Its files come first, and the targets of the recipe are added after them.", + "locale": "The language of the generated content. Only `en` is available, so any other value is refused, and the line can be left out.", + "output": "Where the run writes.", + "output.dir": "The directory for the files and the manifest. A relative path is read from the directory you run in, not from the one the recipe is in. `--out` replaces it.", + "output.manifest": "The file name of the manifest. `manifest.json` unless you say otherwise.", + "output.split_threshold": "Splitting a large manifest into several files. Not built yet: a recipe with this key is refused, and the manifest is always one file.", + "policy": "Rules for settling the expectations that depend on your system. Not built yet: a recipe with this key is refused. Write `expected` on each target instead.", + "seed": "The number every byte of the run comes from. The same seed gives the same files on any machine. `0` unless you say otherwise.", + "targets": "The list of things to produce. Every target needs an `id`, a `format` and exactly one of `size`, `size-range`, `boundary` or `contains`.", + "targets.boundary": "Three files around a limit: one byte under it, the limit itself and one byte over it. Written as a size, such as `5mb`.", + "targets.contains": "For an archive: the files inside it, as a list of entries, each with a `format`, a `count` and a `size`.", + "targets.count": "How many files the target makes. `1` unless you say otherwise.", + "targets.damage": "Ways to break the files on purpose, applied in the order listed. Each one is a name, such as `zero-head`, or a `type` with its settings. `tfg damage` lists them.", + "targets.expected": "What your system should do with these files: `accept`, `reject`, `sanitize` or `unspecified`, alone or with a `reason`. The manifest carries it beside every file.", + "targets.fill": "How the content of these files is made. Not built yet: a recipe with this key is refused.", + "targets.format": "The format of the files, by its id, such as `pdf` or `png`. `tfg formats` lists them.", + "targets.group": "A name of your own for the kind of case these files are. The manifest carries it, so a report can group by it.", + "targets.id": "The name of the target. It is unique in the recipe, the seeds of its files come from it, and the manifest names it beside every file in `target_id`.", + "targets.label": "Whether these files carry the label. Overrides `defaults.label` for this target alone.", + "targets.name": "The template for the file names, such as `invoice_{index:04}.pdf`. `{index:04}` is the number of the file, four digits or more, and the only placeholder there is.", + "targets.properties": "The settings of the format, such as `pages` for a PDF or `width` and `height` for a picture. The page of format settings lists every one.", + "targets.purpose": "A sentence or two on what these files are and why they are in the set. The manifest carries it, and the instructions written beside the manifest are made from it.", + "targets.send-as": "The name to give these files to your system under, when it is one no disk stores, such as `../climbed_out.jpg`. The file keeps an ordinary name on disk, and the manifest carries this one in `send_as`.", + "targets.size": "The exact size of every file, such as `300kb`, `10mb` or a plain byte count. Units count in 1024s. `smallest` makes a picture as small as it can be at its `width` and `height`.", + "targets.size-range": "A size drawn for each file from a range, such as `1kb-8kb`. The draw comes from the seed, so the same seed gives the same sizes.", + "version": "The version of the recipe format. Required, and `1` in this build.", + "with": "The settings of the preset named in `extends`, written the way its flags take them, such as `limit: 5mb`. A setting left out takes its default, and the manifest says so." + }, + "manifestFields": { + "manifest_version": "The version of the manifest format, `1.0`. New fields are added without changing it, so a reader ignores the fields it does not know.", + "generated_at": "When the manifest was written, in UTC.", + "tool": "What made the files.", + "tool.name": "Always `testing-files-generator`.", + "tool.version": "The version of tfg that made the files.", + "tool.go": "The version of Go tfg was built with, so a hash that changed after an upgrade can be traced to it.", + "tool.generators": "The version of the generator of each format the run used, by format. It moves when the bytes a generator writes change.", + "run": "The settings that shaped this run.", + "run.id": "An identifier of this run.", + "run.seed": "The seed of the run. The same seed and the same settings give the same files.", + "run.command": "The command that started the run, as it was typed.", + "run.platform": "Where the run happened.", + "run.platform.os": "The operating system, such as `windows`, `linux` or `darwin`.", + "run.platform.arch": "The processor architecture, such as `amd64` or `arm64`.", + "run.complete": "`false` when the run stopped early, for example after Ctrl+C. The manifest is written even then, so `cleanup` can remove what was made.", + "run.recipe_hash": "The hash of the recipe in its settled shape, so reformatting the recipe keeps it. Present when the run came from a recipe.", + "run.overrides": "The values a flag took over from the recipe, by name. Present when a flag replaced a value of the recipe.", + "run.overrides.*.from_recipe": "The value the recipe gave.", + "run.overrides.*.from_flag": "The value the flag gave, which the run used.", + "run.preset": "The preset the run came from. Present only for a run of a preset.", + "run.preset.id": "The id of the preset.", + "run.preset.question": "The question the preset answers.", + "run.preset.parameters": "Every setting of the preset as the run used it, the ones you gave and its defaults together.", + "run.preset.defaulted": "The settings you did not give, which took the default of the preset. A limit that came from a default is not the limit of your system.", + "run.instructions": "The name of the file written beside the manifest that says in words what each file is and why it is in the set. Present when a file has a purpose.", + "summary": "Counts over the whole run, for a quick check.", + "summary.file_count": "How many entries the manifest has. A run stopped part way lists only the files it finished or that failed, so it can be lower than the files that were planned.", + "summary.total_bytes": "How many bytes the run wrote to disk, in all.", + "summary.materialized": "How many files are on disk. Lower than `file_count` when a name could not be written or a file failed.", + "summary.by_format": "How many files of each format.", + "summary.by_expected": "How many files of each outcome.", + "summary.by_target": "How many files each target made, by target id.", + "files": "One entry for each file of the run.", + "files[].id": "The handle of the file in this manifest, such as `f_0001`, numbered across the whole run.", + "files[].path": "Where the file is, relative to the directory of the manifest. `verify` and `cleanup` find the file by this.", + "files[].name": "The file name, the last part of `path`.", + "files[].send_as": "The name to give the file to your system under, when the recipe asked for one no disk stores. Present only then.", + "files[].materialized": "Whether the file is on disk. A name the system refused is still a test case, and still has its entry.", + "files[].target_id": "The id of the target the file came from.", + "files[].bytes": "The size of the file in bytes.", + "files[].format": "The format of the file.", + "files[].fidelity": "How faithful the file is to its format. `tfg formats` says it for each format.", + "files[].hashes": "The hashes of the file.", + "files[].hashes.sha256": "The SHA-256 of the file, which `verify` compares.", + "files[].seed": "The seed this file was made from, which comes from the seed of the run and the id of the target.", + "files[].generator": "The generator that made the file.", + "files[].generator.name": "The name of the generator.", + "files[].generator.version": "The version of the generator.", + "files[].determinism": "Whether the same seed gives the same bytes, `byte`, or only the same size.", + "files[].properties": "The settings of the format the file was made with, such as its width and height.", + "files[].expected": "What your system should do with the file.", + "files[].expected.outcome": "`accept`, `reject`, `sanitize` or `unspecified`.", + "files[].expected.reason": "The rule in play, from the closed list, such as `size_limit`.", + "files[].expected.detail": "The expectation in words.", + "files[].expected.confidence": "`certain`, or `policy_dependent` when the right reaction depends on how your system is set up.", + "files[].expected.policy_options": "The answers an outcome that depends on your system leaves open, for a test that settles it by your own policy.", + "files[].group": "The group the recipe or the preset gave the file.", + "files[].purpose": "What the file is and why it is in the set, in words.", + "files[].label_embedded": "Whether the file carries the label that says which run made it.", + "files[].damage": "What was broken on purpose, in the order it was done. Absent for a file nothing damaged.", + "files[].damage[].type": "The damage, such as `truncate`.", + "files[].damage[].settings": "Its settings as the run used them, the defaults included.", + "files[].damage[].cut": "Where a cut fell in the file. Present for `truncate`.", + "files[].damage[].cut.in": "What the first byte cut away was part of: `content`, `padding`, `structure` or `end`.", + "files[].damage[].cut.content_bytes": "How long the content of the whole file was, where that is known.", + "files[].damage[].cut.content_kept_bytes": "How much of the content is still in the file.", + "files[].notes": "Things worth knowing about this file, such as a label that did not fit.", + "files[].notes[].code": "A short code for the note, such as `cut_in_padding`.", + "files[].notes[].detail": "The note in words.", + "files[].failed": "`true` for a file the run could not make. The run carries on and ends with exit code `8`.", + "files[].error": "Why the file could not be made." + }, + "recipes": { + "archive-upload": { + "title": "Archive upload", + "text": "ZIP and TAR.GZ archives with real files inside: many entries, files five folders deep, folders listed as entries, an empty archive, one locked with a password and one cut short." + }, + "bulk-files": { + "title": "Bulk files", + "text": "Ten thousand small log files of 1 to 8 KB, for a sync folder, a backup, a file browser or a batch job that meets many files at once." + }, + "ci-smoke": { + "title": "CI smoke test", + "text": "One small file of each common format, well under a megabyte in all, for a quick check in a pipeline that a system reads what it should." + }, + "document-upload": { + "title": "Document upload", + "text": "PDF, Word, Excel, PowerPoint, RTF and text around a 10 MB limit, a 500 page PDF, a corrupt PDF, a Word file cut short, a wrong type and an empty file." + }, + "email-attachments": { + "title": "Email messages", + "text": "EML files with attachments, an inline picture, HTML and plain text, quoted-printable, base64 and windows-1250, a thousand recipients and forwarded mail." + }, + "image-upload": { + "title": "Image upload", + "text": "JPEG, PNG, WebP and GIF around a 5 MB limit, one pixel and 36 megapixels, a corrupt JPEG, a PNG cut short, a PDF named as a photo and a name that climbs out of the folder." + }, + "media-upload": { + "title": "Video and sound upload", + "text": "MP4, WebM and WAV around a 10 MB limit, a portrait phone video, ten minutes of video, silence and a video cut short." + }, + "spreadsheet-import": { + "title": "Spreadsheet import", + "text": "One table as CSV with commas, semicolons and tabs, CRLF, no header and every field quoted, a wide and a large CSV, Excel sheets and two broken files." + } + } } } diff --git a/web/content/es/docs.html b/web/content/es/docs.html index e60c5c9f..9467dd6c 100644 --- a/web/content/es/docs.html +++ b/web/content/es/docs.html @@ -1,284 +1,21 @@

    Documentación

    - Todo lo que hace la herramienta, ordenado según las preguntas con las que la gente llega de verdad. - El README del repositorio es la referencia completa y siempre - coincide con la versión que descargaste. + Cómo instalar tfg, crear tus primeros archivos de prueba y todo lo que el programa acepta y escribe: cada comando y cada opción, cada clave de una receta, cada campo del manifiesto y cada ajuste de cada formato. Estas páginas están en inglés, porque se generan a partir del propio programa cada vez que se construye el sitio, y por eso siempre dicen lo que hace la versión que descargas.

    -
    -

    ¿Qué comandos hay?

    -

    Cada uno hace una sola cosa:

    - {{ template "commandList" . }} -

    - tfg tool reúne las herramientas para archivos que ya tienes, como comprobar un archivo - comprimido antes de descomprimirlo. Herramientas describe cada una. -

    -
    - -
    -

    ¿Cómo genero un único archivo de tamaño exacto?

    -

    - Indica el formato, el tamaño y dónde va. Los tamaños cuentan de 1024 en 1024, así que - 2mb son 2097152 bytes. Un número de bytes simple también sirve, de modo que - --size 10485761 pide exactamente esa cantidad. -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    Las opciones útiles de generate:

    -
    - - - - - - - - - - - - - - - - - -
    OpciónQué hace
    --format <id>formato de los archivos, por ejemplo txt
    --size <size>tamaño exacto de cada archivo, como 10mb o un número de bytes simple
    --size-range <a-b>un tamaño sacado por archivo de un intervalo, como 1kb-8kb. El sorteo viene de la semilla
    --boundary <size>tres archivos alrededor de un límite: un byte por debajo, el límite, un byte por encima
    --count <n>cuántos archivos producir. Por defecto 1
    --name <template>plantilla de nombre, por ejemplo invoice_{index:04}.txt
    --out <dir>directorio donde escribir
    --seed <n>semilla de la ejecución. La misma semilla da los mismos bytes
    --set <k>=<v>un ajuste de formato, repetible
    --damage <name>romper los archivos a propósito, repetible y aplicado en orden. Ejecuta tfg damage para ver la lista
    --expected <outcome>accept, reject, sanitize o unspecified
    --dry-runcontar y mostrar, sin escribir absolutamente nada
    --jsonescribir el manifiesto en la salida estándar
    -
    -
    - -
    -

    ¿Cómo hago un archivo roto a propósito?

    -

    - Todos los demás archivos que escribe esta herramienta son correctos por construcción, lo que - responde a dos de las tres preguntas que hace un validador de subidas. --damage - responde a la tercera - si el archivo se abre siquiera. El archivo se produce con normalidad y - luego se rompe, así que conserva el tamaño que pediste. -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - Los ajustes van después de dos puntos. La opción se repite, y el orden en que las escribes es el - orden en que se aplican. tfg damage lista lo que puede hacer esta versión y qué - admite cada una. -

    -

    En una receta la clave es una lista, de nombres o de ajustes:

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - Un archivo dañado recibe expected: reject en el manifiesto, con el daño registrado a su - lado. Dos cosas se rechazan antes de escribir nada, porque cada una dejaría en disco un archivo - que el manifiesto describe mal: -

    -
      -
    • un archivo más pequeño de lo que necesita el daño, porque saldría sin cambios
    • -
    • - expected: accept junto a un daño, porque nada podría cumplirlo. Escribe - sanitize si el sistema bajo prueba debe reparar el archivo, o - unspecified si esa es la pregunta que haces -
    • -
    -

    - Una tercera no se puede saber de antemano. Si un daño se ejecuta y no mueve ningún byte, ese archivo - se descarta en lugar de escribirse - la ejecución continúa, dice de qué archivo se trató y - termina con el código de salida parcial. -

    -

    - Paso a paso, con una prueba que lee el manifiesto: cómo - crear un archivo corrupto para pruebas. -

    +
    +

    Páginas de la documentación

    + {{ template "linkCards" .Docs }}
    -
    -

    ¿Qué aspecto tiene una receta?

    -

    - Una receta es un archivo YAML que describe una ejecución completa. Súbela al repositorio junto a tus - pruebas y los fixtures dejan de ser binarios en tu repositorio - cualquiera puede - reconstruirlos, byte a byte, a partir de un archivo de unos cientos de caracteres. -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - Cada target necesita exactamente una de estas claves: size, size-range, - boundary o contains. Dos es un error y ninguna también. Una receta - inválida escribe ningún archivo e informa de todos los problemas a la vez en - lugar de solo del primero, cada uno nombrando el ajuste al que se refiere. -

    +
    +

    Qué hace la herramienta, tema por tema

    + {{ template "linkCards" (.PagesOf "formats" "presets" "damage" "samples" "upload-tests" "ci" "exact-size") }}
    -
    -

    ¿Cómo declaro qué debe hacer mi sistema con un archivo?

    -

    Forma corta cuando basta con el resultado, forma larga cuando importa el motivo:

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - Los resultados son accept, reject, sanitize y - unspecified. Los motivos son una lista cerrada para que un informe pueda - agruparlos: content_malformed, count_limit, - dimensions_limit, duplicate, encoding_invalid, - extension_rule, filename_invalid, filename_too_long, - filename_traversal, malware_signature, mime_mismatch, - nesting_depth, none, size_limit y size_zero. -

    -

    - Un motivo nombra la regla en juego, no el veredicto. Por eso el mismo motivo puede - estar bajo cualquiera de los dos resultados - un archivo un byte por debajo de un límite es - accept, y la regla de la que trata sigue siendo size_limit. -

    -
    - -
    -

    ¿Qué hay en el manifiesto?

    -

    - Se escribe junto a los archivos al final de cada ejecución, incluida una ejecución interrumpida. Una - entrada por archivo: -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "{{ .Facts.Version }}" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - Se añade un recipe_hash cuando la ejecución viene de una receta, y preset - con overrides cuando viene de un preset, de modo que un manifiesto siempre se puede - rastrear hasta lo que lo produjo. -

    -

    - Cada entrada lleva también target_id, el id del target de la receta que produjo el - archivo, y summary.by_target cuenta los archivos a los que llegó cada target. Una - receta con varios targets se puede comprobar así target por target sin leer nombres de archivo. -

    -
    - -
    -

    ¿Qué es un preset?

    -

    - Un conjunto de archivos listo que responde a una pregunta de prueba habitual, para que no tengas que - diseñar el conjunto tú. Los presets son recetas normales por debajo, y eject - imprime la receta para que la edites desde ahí. Cada preset tiene una - página propia con lo que suele encontrar, qué hay en el conjunto y cada ajuste que admite. -

    - {{ template "presetsList" . }} -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show te dice cuánto costaría el conjunto antes de construirlo, y dice sin rodeos cuándo - un número es un marcador nuestro en lugar de un límite tuyo. -

    -
    - -
    -

    ¿Qué significan los códigos de salida?

    -

    - Cada final tiene su propio código, la salida legible por máquina va a la salida estándar, y una - ejecución fallida no imprime nada allí. La tabla es un contrato congelado - cambiar lo que - significa un código exige una versión mayor. -

    - {{ template "exitCodesTable" . }} -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - Una ejecución detenida con Ctrl+C sigue dejando un manifiesto y nunca deja un archivo a medio - escribir, así que un trabajo cancelado aún puede limpiarlo el siguiente. -

    -

    - Workflows listos para GitHub Actions y GitLab CI: cómo - generar archivos de prueba en un pipeline de CI. -

    -
    - -
    -

    ¿Hay una ventana de escritorio?

    -

    - Sí, el mismo motor con una ventana encima, para las pruebas que no se automatizan. No es una versión - recortada: una prueba compara las dos interfaces capacidad por capacidad, y todo lo que solo una - de ellas puede hacer debe declararse y justificarse en lugar de divergir en silencio. -

    +
    +

    ¿Sigues atascado?

    - Las pantallas son un lote, presets, varios lotes a la vez y Acerca de. Muestra lo que costaría una - ejecución antes de escribir nada, informa del progreso mientras corre y se puede cancelar a - medias sin dejar un archivo a medio escribir. Todavía no abre un archivo de receta - por ahora - las recetas son cosa de la línea de comandos, y la ventana construye sus lotes en el formulario. + tfg <command> --help muestra en la terminal lo que acepta un comando. Cada rechazo nombra el ajuste al que se refiere, el motivo y un valor que funcionaría. Si algo no se comporta como dice una página, avísanos. Es un error de la página o del programa.

    diff --git a/web/content/es/site.json b/web/content/es/site.json index 88ffaed2..e96a5f25 100644 --- a/web/content/es/site.json +++ b/web/content/es/site.json @@ -138,7 +138,8 @@ "colSha256": "SHA-256", "colExpected": "Esperado", "colTool": "Herramienta", - "colQuestion": "Qué responde" + "colQuestion": "Qué responde", + "docsMenuLabel": "Páginas de la documentación" }, "endings": { "0": "Todo ha funcionado.", @@ -386,5 +387,45 @@ "checksum": "¿Es este archivo el que dice ser?", "checksum-check": "¿Sigue cada archivo coincidiendo con lo que dice su archivo de sumas de comprobación?", "checksum-write": "¿Cómo sabré más tarde que ninguno de estos archivos ha cambiado?" + }, + "docs": { + "guides": { + "guide-install": { + "title": "Instalación", + "text": "Descargar para Windows, macOS o Linux, comprobar el archivo o instalar con Docker, npm, pip o Go." + }, + "guide-start": { + "title": "Primeros pasos", + "text": "Un primer archivo de tamaño exacto, luego diez mil, comprobados, borrados y escritos como receta." + }, + "guide-commands": { + "title": "Comandos", + "text": "Cada comando y cada opción con su valor por defecto, y todos los códigos de salida." + }, + "guide-recipes": { + "title": "Escribir recetas", + "text": "Cada clave de una receta, tamaños, nombres de archivo, reacciones esperadas, daños, archivos comprimidos y presets." + }, + "recipes": { + "title": "Galería de recetas", + "text": "Recetas listas para descargar para subidas, importaciones, archivos comprimidos, correo, multimedia, CI y archivos en masa." + }, + "guide-manifest": { + "title": "Manifiesto", + "text": "Cada campo de manifest.json y cómo lo lee una prueba." + }, + "guide-formats": { + "title": "Ajustes de formato", + "text": "Cada ajuste de cada formato, con los valores que acepta y su valor por defecto." + }, + "guide-frameworks": { + "title": "Frameworks de pruebas", + "text": "Los archivos dentro de pytest, Playwright, Vitest y node:test." + }, + "guide-window": { + "title": "Aplicación de escritorio", + "text": "La ventana, pantalla por pantalla." + } + } } } diff --git a/web/content/fr/docs.html b/web/content/fr/docs.html index b3f9769e..e22082a5 100644 --- a/web/content/fr/docs.html +++ b/web/content/fr/docs.html @@ -1,292 +1,21 @@

    Documentation

    - Tout ce que fait l'outil, rangé selon les questions avec lesquelles les gens arrivent vraiment. Le - README du dépôt est la référence complète et correspond toujours à - la version que vous avez téléchargée. + Comment installer tfg, créer vos premiers fichiers de test, et tout ce que le programme accepte et écrit : chaque commande et chaque option, chaque clé d'une recette, chaque champ du manifeste et chaque réglage de chaque format. Ces pages sont en anglais, car elles sont produites par le programme lui-même à chaque construction du site, et disent donc toujours ce que fait la version que vous téléchargez.

    -
    -

    Quelles commandes existe-t-il ?

    -

    Chacune fait une seule chose :

    - {{ template "commandList" . }} -

    - tfg tool regroupe les outils pour les fichiers que vous avez déjà, comme la - vérification d'une archive avant de la décompresser. Outils décrit chacun - d'eux. -

    -
    - -
    -

    Comment générer un seul fichier de taille exacte ?

    -

    - Nommez le format, la taille et la destination. Les tailles se comptent par 1024, donc - 2mb font 2097152 octets. Un nombre d'octets brut fonctionne aussi, donc - --size 10485761 demande exactement ce nombre. -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    Les options utiles de generate :

    -
    - - - - - - - - - - - - - - - - - -
    OptionCe qu'elle fait
    --format <id>format des fichiers, par exemple txt
    --size <size>taille exacte de chaque fichier, comme 10mb ou un nombre d'octets brut
    --size-range <a-b>une taille tirée par fichier dans une plage, comme 1kb-8kb. Le tirage vient de la graine
    --boundary <size>trois fichiers autour d'une limite : un octet en dessous, la limite, un octet au-dessus
    --count <n>combien de fichiers produire. Par défaut 1
    --name <template>modèle de nom, par exemple invoice_{index:04}.txt
    --out <dir>répertoire où écrire
    --seed <n>graine de l'exécution. La même graine donne les mêmes octets
    --set <k>=<v>un réglage de format, répétable
    --damage <name>abîmer les fichiers exprès, répétable et appliqué dans l'ordre. Lancez tfg damage pour la liste
    --expected <outcome>accept, reject, sanitize ou unspecified
    --dry-runcompter et montrer, sans rien écrire du tout
    --jsonécrire le manifeste sur la sortie standard
    -
    -
    - -
    -

    Comment fabriquer un fichier volontairement cassé ?

    -

    - Tout autre fichier écrit par cet outil est correct par construction, ce qui répond à deux des trois - questions que pose un validateur d'envoi. --damage répond à la troisième - le - fichier s'ouvre-t-il seulement. Le fichier est produit normalement puis abîmé, il garde donc la - taille demandée. -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - Les réglages se placent après deux-points. L'option se répète, et l'ordre dans lequel vous les - écrivez est l'ordre dans lequel ils sont appliqués. tfg damage liste ce que cette - version sait faire et ce que chacun accepte. -

    -

    Dans une recette, la clé est une liste, de noms ou de réglages :

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - Un fichier abîmé reçoit expected: reject dans le manifeste, avec l'altération notée à - côté. Deux choses sont refusées avant que rien ne soit écrit, car chacune mettrait sinon sur le - disque un fichier que le manifeste décrit à tort : -

    -
      -
    • un fichier plus petit que ce dont l'altération a besoin, car il ressortirait inchangé
    • -
    • - expected: accept à côté d'une altération, car rien ne pourrait y répondre. Écrivez - sanitize si le système testé doit réparer le fichier, ou unspecified - si c'est justement la question que vous posez -
    • -
    -

    - Une troisième ne peut pas être connue à l'avance. Si une altération s'exécute sans déplacer un seul - octet, ce fichier est abandonné plutôt qu'écrit - l'exécution continue, dit de quel fichier il - s'agissait et se termine avec le code de sortie partiel. -

    -

    - Pas à pas, avec un test qui lit le manifeste : - comment fabriquer un fichier corrompu pour les - tests. -

    +
    +

    Pages de la documentation

    + {{ template "linkCards" .Docs }}
    -
    -

    À quoi ressemble une recette ?

    -

    - Une recette est un fichier YAML qui décrit toute une exécution. Commitez-la à côté de vos tests et - les fixtures cessent d'être des binaires dans votre dépôt - n'importe qui peut les reconstruire, - à l'octet près, à partir d'un fichier de quelques centaines de caractères. -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - Chaque cible exige exactement une de ces clés : size, size-range, - boundary ou contains. Deux est une erreur, et aucune aussi. Une - recette invalide n'écrit aucun fichier et signale tous les problèmes d'un coup - plutôt que le premier seulement, chacun nommant le réglage concerné. -

    +
    +

    Ce que fait l'outil, sujet par sujet

    + {{ template "linkCards" (.PagesOf "formats" "presets" "damage" "samples" "upload-tests" "ci" "exact-size") }}
    -
    -

    Comment déclarer ce que mon système doit faire d'un fichier ?

    -

    Forme courte quand le résultat suffit, forme longue quand la raison compte :

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - Les résultats sont accept, reject, sanitize et - unspecified. Les raisons forment une liste fermée pour qu'un rapport puisse les - regrouper : content_malformed, count_limit, - dimensions_limit, duplicate, encoding_invalid, - extension_rule, filename_invalid, filename_too_long, - filename_traversal, malware_signature, mime_mismatch, - nesting_depth, none, size_limit et - size_zero. -

    -

    - Une raison nomme la règle en jeu, pas le verdict. C'est pourquoi la même raison - peut se trouver sous l'un ou l'autre résultat - un fichier un octet sous une limite est - accept, et la règle concernée reste size_limit. -

    -
    - -
    -

    Que contient le manifeste ?

    -

    - Il est écrit à côté des fichiers à la fin de chaque exécution, y compris d'une exécution - interrompue. Une entrée par fichier : -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "{{ .Facts.Version }}" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - Un recipe_hash est ajouté quand l'exécution vient d'une recette, et preset - avec overrides quand elle vient d'un préréglage, de sorte qu'un manifeste peut - toujours être rattaché à ce qui l'a produit. -

    -

    - Chaque entrée porte aussi target_id, l'identifiant de la cible de la recette qui a - produit le fichier, et summary.by_target compte les fichiers de chaque cible. Une - recette à plusieurs cibles peut donc être vérifiée cible par cible sans lire les noms de - fichiers. -

    -
    - -
    -

    Qu'est-ce qu'un préréglage ?

    -

    - Un jeu de fichiers prêt à l'emploi qui répond à une question de test courante, pour que vous n'ayez - pas à concevoir le jeu vous-même. Les préréglages sont des recettes ordinaires en dessous, et - eject affiche la recette pour que vous puissiez la modifier. Chaque préréglage a - sa propre page qui dit ce qu'il trouve d'habitude, ce que - contient le jeu et chaque réglage qu'il accepte. -

    - {{ template "presetsList" . }} -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show vous dit ce que coûterait le jeu avant que vous ne le construisiez, et dit - franchement quand un nombre est un substitut de notre part plutôt qu'une limite de la vôtre. -

    -
    - -
    -

    Que signifient les codes de sortie ?

    -

    - Chaque fin a son propre code, la sortie lisible par machine va sur la sortie standard, et une - exécution échouée n'y écrit rien. Le tableau est un contrat figé - changer le sens d'un code - exige une version majeure. -

    - {{ template "exitCodesTable" . }} -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - Une exécution arrêtée avec Ctrl+C laisse quand même un manifeste et ne laisse jamais de fichier à - moitié écrit, si bien qu'une tâche annulée peut encore être nettoyée par la suivante. -

    -

    - Des workflows prêts pour GitHub Actions et GitLab CI : - comment générer des fichiers de test dans un pipeline - CI. -

    -
    - -
    -

    Y a-t-il une fenêtre de bureau ?

    -

    - Oui, le même moteur avec une fenêtre, pour les tests qui ne sont pas scriptés. Ce n'est pas une - version amputée : un test compare les deux interfaces fonctionnalité par fonctionnalité, et - tout ce que seule l'une peut faire doit être déclaré et justifié au lieu de diverger - discrètement. -

    +
    +

    Toujours bloqué ?

    - Les écrans sont un lot, les préréglages, plusieurs lots à la fois et À propos. Elle montre ce que - coûterait une exécution avant d'écrire quoi que ce soit, indique la progression pendant - l'exécution et peut être annulée en cours de route sans laisser de fichier à moitié écrit. Elle - n'ouvre pas encore de fichier de recette - les recettes sont pour l'instant une affaire de ligne - de commande, et la fenêtre construit ses lots dans le formulaire. + tfg <command> --help indique dans le terminal ce qu'une commande accepte. Chaque refus nomme le réglage concerné, la raison et une valeur qui fonctionnerait. Si quelque chose ne se comporte pas comme une page le dit, signalez-le. C'est une erreur de la page ou du programme.

    diff --git a/web/content/fr/site.json b/web/content/fr/site.json index 1696cfee..0e759ce7 100644 --- a/web/content/fr/site.json +++ b/web/content/fr/site.json @@ -138,7 +138,8 @@ "colSha256": "SHA-256", "colExpected": "Attendu", "colTool": "Outil", - "colQuestion": "La question à laquelle il répond" + "colQuestion": "La question à laquelle il répond", + "docsMenuLabel": "Pages de la documentation" }, "endings": { "0": "Tout a fonctionné.", @@ -386,5 +387,45 @@ "checksum": "Ce fichier est-il bien celui qu'il prétend être ?", "checksum-check": "Chaque fichier est-il toujours ce que dit son fichier de sommes de contrôle ?", "checksum-write": "Comment saurai-je plus tard qu'aucun de ces fichiers n'a changé ?" + }, + "docs": { + "guides": { + "guide-install": { + "title": "Installation", + "text": "Télécharger pour Windows, macOS ou Linux, vérifier l'archive, ou installer avec Docker, npm, pip ou Go." + }, + "guide-start": { + "title": "Premiers pas", + "text": "Un premier fichier de taille exacte, puis dix mille, vérifiés, supprimés et décrits dans une recette." + }, + "guide-commands": { + "title": "Commandes", + "text": "Chaque commande et chaque option avec sa valeur par défaut, et tous les codes de sortie." + }, + "guide-recipes": { + "title": "Écrire une recette", + "text": "Chaque clé d'une recette, les tailles, les noms de fichiers, les réactions attendues, les dommages, les archives et les presets." + }, + "recipes": { + "title": "Galerie de recettes", + "text": "Des recettes prêtes à télécharger pour les envois, les imports, les archives, les e-mails, les médias, la CI et les fichiers en masse." + }, + "guide-manifest": { + "title": "Manifeste", + "text": "Chaque champ de manifest.json, et comment un test le lit." + }, + "guide-formats": { + "title": "Réglages des formats", + "text": "Chaque réglage de chaque format, avec les valeurs acceptées et la valeur par défaut." + }, + "guide-frameworks": { + "title": "Frameworks de test", + "text": "Les fichiers dans pytest, Playwright, Vitest et node:test." + }, + "guide-window": { + "title": "Application de bureau", + "text": "La fenêtre, écran par écran." + } + } } } diff --git a/web/content/hi/docs.html b/web/content/hi/docs.html index 5e6173a0..f4268677 100644 --- a/web/content/hi/docs.html +++ b/web/content/hi/docs.html @@ -1,282 +1,21 @@

    दस्तावेज़ीकरण

    - टूल जो कुछ भी करता है, उन सवालों के रूप में सजाया गया जिन्हें लेकर लोग सच में आते हैं। - रिपॉज़िटरी का README पूरा संदर्भ है और हमेशा आपके डाउनलोड किए - बिल्ड से मेल खाता है। + tfg कैसे इंस्टॉल करें, अपनी पहली टेस्ट फ़ाइलें कैसे बनाएँ, और वह सब कुछ जो प्रोग्राम लेता और लिखता है: हर कमांड और हर फ़्लैग, रेसिपी की हर कुंजी, मैनिफ़ेस्ट का हर फ़ील्ड और हर फ़ॉर्मैट की हर सेटिंग। ये पेज अंग्रेज़ी में हैं, क्योंकि साइट हर बार बनते समय ये प्रोग्राम से ही बनते हैं, इसलिए हमेशा वही बताते हैं जो आपका डाउनलोड किया संस्करण करता है।

    -
    -

    कौन सी कमांड हैं?

    -

    हर एक सिर्फ़ एक काम करती है:

    - {{ template "commandList" . }} -

    - tfg tool में आपके पास पहले से मौजूद फ़ाइलों के लिए टूल हैं, जैसे किसी आर्काइव को - एक्सट्रैक्ट करने से पहले जाँचना। टूल पेज हर एक के बारे में बताता है। -

    -
    - -
    -

    सटीक आकार की एक फ़ाइल कैसे बनाऊँ?

    -

    - फ़ॉर्मैट, आकार और जगह बताएँ। आकार 1024 के गुणकों में गिने जाते हैं, इसलिए 2mb 2097152 - बाइट है। सादी बाइट संख्या भी चलती है, इसलिए --size 10485761 ठीक उतने ही बाइट माँगता - है। -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    generate के काम के फ़्लैग:

    -
    - - - - - - - - - - - - - - - - - -
    फ़्लैगक्या करता है
    --format <id>फ़ाइलों का फ़ॉर्मैट, जैसे txt
    --size <size>हर फ़ाइल का सटीक आकार, जैसे 10mb या सादी बाइट संख्या
    --size-range <a-b>किसी सीमा में से हर फ़ाइल के लिए निकाला गया आकार, जैसे 1kb-8kb। निकालना सीड से होता है
    --boundary <size>सीमा के आसपास तीन फ़ाइलें: एक बाइट नीचे, सीमा, एक बाइट ऊपर
    --count <n>कितनी फ़ाइलें बनानी हैं। डिफ़ॉल्ट 1
    --name <template>नाम का साँचा, जैसे invoice_{index:04}.txt
    --out <dir>जिस डायरेक्टरी में लिखना है
    --seed <n>रन का सीड। वही सीड वही बाइट देता है
    --set <k>=<v>फ़ॉर्मैट की एक सेटिंग, दोहराई जा सकती है
    --damage <name>फ़ाइलों को जानबूझकर बिगाड़ें, दोहराया जा सकता है और क्रम से लागू होता है। सूची के लिए tfg damage चलाएँ
    --expected <outcome>accept, reject, sanitize या unspecified
    --dry-runगिनें और दिखाएँ, कुछ भी न लिखें
    --jsonमैनिफ़ेस्ट को स्टैंडर्ड आउटपुट पर लिखें
    -
    -
    - -
    -

    जानबूझकर टूटी फ़ाइल कैसे बनाऊँ?

    -

    - यह टूल जो भी दूसरी फ़ाइल लिखता है वह बनावट से सही होती है, और इससे अपलोड वैलिडेटर के तीन सवालों में - से दो का जवाब मिल जाता है। --damage तीसरे का जवाब देता है - क्या फ़ाइल खुलती भी है। - फ़ाइल सामान्य रूप से बनती है और फिर बिगाड़ी जाती है, इसलिए उसका आकार वही रहता है जो आपने माँगा। -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - सेटिंग कोलन के बाद आती हैं। फ़्लैग दोहराया जा सकता है, और आप जिस क्रम में लिखते हैं वही उनके लागू - होने का क्रम है। tfg damage बताता है कि यह बिल्ड क्या कर सकता है और हर एक क्या लेता - है। -

    -

    रेसिपी में कुंजी एक सूची है, नामों की या सेटिंग की:

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - बिगाड़ी गई फ़ाइल को मैनिफ़ेस्ट में expected: reject मिलता है, और बिगाड़ने का ब्योरा - उसके बगल में दर्ज होता है। दो चीज़ें कुछ भी लिखे जाने से पहले ठुकरा दी जाती हैं, क्योंकि हर एक - डिस्क पर ऐसी फ़ाइल छोड़ देती जिसे मैनिफ़ेस्ट गलत बताता: -

    -
      -
    • बिगाड़ने के लिए ज़रूरी से छोटी फ़ाइल, क्योंकि वह बिना बदले निकल आती
    • -
    • - बिगाड़ के बगल में expected: accept, क्योंकि कुछ भी उसे पूरा नहीं कर सकता। अगर जाँचे जा - रहे सिस्टम को फ़ाइल सुधारनी है तो sanitize लिखें, या अगर आप यही सवाल पूछ रहे हैं - तो unspecified -
    • -
    -

    - तीसरी बात पहले से नहीं जानी जा सकती। अगर कोई बिगाड़ चलता है और एक भी बाइट नहीं हिलाता, तो वह फ़ाइल - लिखे जाने के बजाय छोड़ दी जाती है - रन चलता रहता है, बताता है कि वह कौन सी फ़ाइल थी, और आंशिक - एग्ज़िट कोड के साथ ख़त्म होता है। -

    -

    - कदम दर कदम, मैनिफ़ेस्ट पढ़ने वाले एक टेस्ट के साथ: परीक्षण के लिए - खराब फ़ाइल कैसे बनाएँ। -

    +
    +

    दस्तावेज़ीकरण के पेज

    + {{ template "linkCards" .Docs }}
    -
    -

    रेसिपी कैसी दिखती है?

    -

    - रेसिपी एक YAML फ़ाइल है जो पूरे रन का वर्णन करती है। इसे अपने टेस्ट के बगल में कमिट करें और - फ़िक्स्चर आपकी रिपॉज़िटरी में बाइनरी नहीं रह जाते - कोई भी उन्हें कुछ सौ अक्षरों की फ़ाइल से - बाइट-दर-बाइट दोबारा बना सकता है। -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - हर टार्गेट को size, size-range, boundary या - contains में से ठीक एक चाहिए। दो होना त्रुटि है और एक भी न होना भी। अमान्य रेसिपी - कोई फ़ाइल नहीं लिखती और सिर्फ़ पहली नहीं, सारी समस्याएँ एक साथ बताती है, हर एक - उस सेटिंग का नाम लेकर जिससे वह जुड़ी है। -

    +
    +

    टूल क्या करता है, विषय के अनुसार

    + {{ template "linkCards" (.PagesOf "formats" "presets" "damage" "samples" "upload-tests" "ci" "exact-size") }}
    -
    -

    मैं कैसे बताऊँ कि मेरे सिस्टम को किसी फ़ाइल के साथ क्या करना चाहिए?

    -

    जब नतीजा काफ़ी हो तो छोटा रूप, जब कारण मायने रखे तो लंबा रूप:

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - नतीजे हैं accept, reject, sanitize और - unspecified। कारण एक बंद सूची हैं ताकि रिपोर्ट उनके आधार पर समूह बना सके: - content_malformed, count_limit, dimensions_limit, - duplicate, encoding_invalid, extension_rule, - filename_invalid, filename_too_long, filename_traversal, - malware_signature, mime_mismatch, nesting_depth, - none, size_limit और size_zero। -

    -

    - कारण काम कर रहे नियम का नाम लेता है, फ़ैसले का नहीं। इसीलिए एक ही कारण किसी भी - नतीजे के नीचे आ सकता है - सीमा से एक बाइट नीचे की फ़ाइल accept है, और जिस नियम की - बात है वह फिर भी size_limit है। -

    -
    - -
    -

    मैनिफ़ेस्ट में क्या है?

    -

    - यह हर रन के अंत में फ़ाइलों के बगल में लिखा जाता है, बीच में रोके गए रन में भी। हर फ़ाइल के लिए एक - प्रविष्टि: -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "{{ .Facts.Version }}" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - रन रेसिपी से आया हो तो recipe_hash जुड़ता है, और प्रीसेट से आया हो तो - overrides के साथ preset, इसलिए मैनिफ़ेस्ट को हमेशा उसके स्रोत तक खोजा - जा सकता है। -

    -

    - हर प्रविष्टि में target_id भी होता है, यानी रेसिपी के उस टार्गेट का id जिसने फ़ाइल - बनाई, और summary.by_target गिनता है कि हर टार्गेट के हिस्से कितनी फ़ाइलें आईं। - इसलिए कई टार्गेट वाली रेसिपी को फ़ाइल नाम पढ़े बिना टार्गेट-दर-टार्गेट जाँचा जा सकता है। -

    -
    - -
    -

    प्रीसेट क्या है?

    -

    - किसी आम टेस्ट सवाल का जवाब देने वाला फ़ाइलों का तैयार सेट, ताकि आपको सेट खुद डिज़ाइन न करना पड़े। - प्रीसेट अंदर से सामान्य रेसिपी हैं, और eject रेसिपी छापता है ताकि आप वहीं से उसे - संपादित कर सकें। हर प्रीसेट का अपना पेज है जो बताता है कि वह आम तौर - पर क्या पकड़ता है, सेट में क्या है और वह कौन सी सेटिंग लेता है। -

    - {{ template "presetsList" . }} -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show सेट बनाने से पहले बताता है कि उसकी क़ीमत क्या होगी, और साफ़ कहता है जब कोई संख्या - आपकी सीमा नहीं बल्कि हमारी अस्थायी जगह-धारक संख्या हो। -

    -
    - -
    -

    एग्ज़िट कोड का क्या अर्थ है?

    -

    - हर अंत का अपना कोड है, मशीन के पढ़ने लायक आउटपुट स्टैंडर्ड आउटपुट पर जाता है, और विफल रन वहाँ कुछ - नहीं छापता। तालिका एक जमाया हुआ अनुबंध है - किसी कोड का अर्थ बदलने के लिए मुख्य संस्करण बढ़ाना - पड़ता है। -

    - {{ template "exitCodesTable" . }} -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - Ctrl+C से रोका गया रन फिर भी मैनिफ़ेस्ट छोड़ता है और कभी आधी लिखी फ़ाइल नहीं छोड़ता, इसलिए रद्द किए - गए जॉब को अगला जॉब साफ़ कर सकता है। -

    -

    - GitHub Actions और GitLab CI के लिए तैयार वर्कफ़्लो: CI पाइपलाइन में - टेस्ट फ़ाइलें कैसे बनाएँ। -

    -
    - -
    -

    क्या डेस्कटॉप विंडो है?

    -

    - हाँ, वही इंजन जिस पर एक विंडो लगी है, उस टेस्टिंग के लिए जो स्क्रिप्ट से नहीं होती। यह घटाया हुआ रूप - नहीं है: एक टेस्ट दोनों इंटरफ़ेस की क्षमता-दर-क्षमता तुलना करता है, और जो सिर्फ़ एक ही कर सकता - है उसे चुपचाप अलग होने देने के बजाय घोषित और उचित ठहराना पड़ता है। -

    +
    +

    अब भी अटके हैं?

    - स्क्रीन हैं एक बैच, प्रीसेट, एक साथ कई बैच, और परिचय। यह कुछ भी लिखने से पहले रन की क़ीमत दिखाती है, - चलते समय प्रगति बताती है, और बीच में रद्द की जा सकती है बिना आधी लिखी फ़ाइल छोड़े। यह अभी रेसिपी - फ़ाइल नहीं खोलती - फ़िलहाल रेसिपी कमांड लाइन की चीज़ हैं, और विंडो अपने बैच फ़ॉर्म में बनाती है। + tfg <command> --help टर्मिनल में बताता है कि कोई कमांड क्या लेता है। हर अस्वीकृति बताती है कि बात किस सेटिंग की है, कारण क्या है और कौन-सा मान चलेगा। अगर कुछ वैसा व्यवहार नहीं करता जैसा यहाँ कोई पेज कहता है, तो हमें बताएँ। वह पेज या प्रोग्राम की गलती है।

    diff --git a/web/content/hi/site.json b/web/content/hi/site.json index 04363e38..7939e51c 100644 --- a/web/content/hi/site.json +++ b/web/content/hi/site.json @@ -138,7 +138,8 @@ "colSha256": "SHA-256", "colExpected": "अपेक्षित", "colTool": "टूल", - "colQuestion": "किस सवाल का जवाब देता है" + "colQuestion": "किस सवाल का जवाब देता है", + "docsMenuLabel": "दस्तावेज़ीकरण के पेज" }, "endings": { "0": "सब कुछ ठीक चला।", @@ -386,5 +387,45 @@ "checksum": "क्या यह फ़ाइल वही है जो होने का दावा करती है?", "checksum-check": "क्या हर फ़ाइल अब भी वैसी ही है जैसा उसकी चेकसम फ़ाइल कहती है?", "checksum-write": "बाद में मुझे कैसे पता चलेगा कि इनमें से कोई भी फ़ाइल नहीं बदली?" + }, + "docs": { + "guides": { + "guide-install": { + "title": "इंस्टॉल करना", + "text": "Windows, macOS या Linux के लिए डाउनलोड करें, आर्काइव जाँचें, या Docker, npm, pip या Go से इंस्टॉल करें।" + }, + "guide-start": { + "title": "शुरुआत", + "text": "सटीक आकार की पहली फ़ाइल, फिर दस हज़ार, जाँची गईं, हटाई गईं और रेसिपी के रूप में लिखी गईं।" + }, + "guide-commands": { + "title": "कमांड", + "text": "हर कमांड और हर फ़्लैग अपने डिफ़ॉल्ट मान के साथ, और सभी एग्ज़िट कोड।" + }, + "guide-recipes": { + "title": "रेसिपी लिखना", + "text": "रेसिपी की हर कुंजी, आकार, फ़ाइल नाम, अपेक्षित प्रतिक्रियाएँ, क्षति, आर्काइव और प्रीसेट।" + }, + "recipes": { + "title": "रेसिपी संग्रह", + "text": "अपलोड, इंपोर्ट, आर्काइव, ईमेल, मीडिया, CI और बड़ी संख्या की फ़ाइलों के लिए डाउनलोड करने को तैयार रेसिपी।" + }, + "guide-manifest": { + "title": "मैनिफ़ेस्ट", + "text": "manifest.json का हर फ़ील्ड और टेस्ट उसे कैसे पढ़ता है।" + }, + "guide-formats": { + "title": "फ़ॉर्मैट सेटिंग", + "text": "हर फ़ॉर्मैट की हर सेटिंग, स्वीकार्य मानों और डिफ़ॉल्ट मान के साथ।" + }, + "guide-frameworks": { + "title": "टेस्ट फ़्रेमवर्क", + "text": "pytest, Playwright, Vitest और node:test के अंदर फ़ाइलें।" + }, + "guide-window": { + "title": "डेस्कटॉप ऐप", + "text": "प्रोग्राम की विंडो, एक-एक स्क्रीन करके।" + } + } } } diff --git a/web/content/id/docs.html b/web/content/id/docs.html index 79081e92..09022320 100644 --- a/web/content/id/docs.html +++ b/web/content/id/docs.html @@ -1,287 +1,21 @@

    Dokumentasi

    - Semua yang dilakukan alat ini, disusun sebagai pertanyaan yang benar-benar dibawa orang. - README di repositori adalah referensi lengkap dan selalu sesuai - dengan build yang Anda unduh. + Cara memasang tfg, membuat berkas uji pertama Anda, dan semua yang diterima dan ditulis program: setiap perintah dan setiap opsi, setiap kunci resep, setiap bidang manifes, dan setiap pengaturan setiap format. Halaman-halaman ini berbahasa Inggris, karena dibuat dari program itu sendiri setiap kali situs dibangun, sehingga selalu sesuai dengan versi yang Anda unduh.

    -
    -

    Perintah apa saja yang ada?

    -

    Masing-masing melakukan satu hal:

    - {{ template "commandList" . }} -

    - tfg tool berisi alat untuk file yang sudah Anda miliki, misalnya memeriksa arsip - sebelum diekstrak. Alat menjelaskan masing-masing. -

    -
    - -
    -

    Bagaimana cara membuat satu file dengan ukuran tepat?

    -

    - Sebutkan format, ukuran, dan tujuannya. Ukuran dihitung dalam kelipatan 1024, jadi 2mb - adalah 2097152 byte. Jumlah byte biasa juga bisa, jadi --size 10485761 meminta - persis sebanyak itu. -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    Opsi yang berguna pada generate:

    -
    - - - - - - - - - - - - - - - - - -
    OpsiFungsinya
    --format <id>format file, misalnya txt
    --size <size>ukuran tepat setiap file, seperti 10mb atau jumlah byte biasa
    --size-range <a-b>ukuran yang diundi per file dari suatu rentang, seperti 1kb-8kb. Undiannya berasal dari seed
    --boundary <size>tiga file di sekitar batas: satu byte di bawah, batas itu sendiri, satu byte di atas
    --count <n>berapa banyak file yang dibuat. Bawaan 1
    --name <template>templat nama, misalnya invoice_{index:04}.txt
    --out <dir>direktori tujuan penulisan
    --seed <n>seed run. Seed yang sama menghasilkan byte yang sama
    --set <k>=<v>pengaturan format, dapat diulang
    --damage <name>merusak file dengan sengaja, dapat diulang dan diterapkan berurutan. Jalankan tfg damage untuk daftarnya
    --expected <outcome>accept, reject, sanitize, atau unspecified
    --dry-runmenghitung dan menampilkan, tidak menulis apa pun
    --jsonmenulis manifes ke keluaran standar
    -
    -
    - -
    -

    Bagaimana membuat file yang sengaja dirusak?

    -

    - Setiap file lain yang ditulis alat ini benar menurut konstruksinya, yang menjawab dua dari tiga - pertanyaan yang diajukan validator unggahan. --damage menjawab yang ketiga - apakah - file itu dapat dibuka sama sekali. File dibuat secara normal lalu dirusak, sehingga ukurannya - tetap seperti yang Anda minta. -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - Pengaturan ditulis setelah titik dua. Opsinya dapat diulang, dan urutan penulisannya adalah urutan - penerapannya. tfg damage mendaftar apa yang bisa dilakukan build ini dan apa yang - diterima masing-masing. -

    -

    Dalam resep, kuncinya adalah daftar, berisi nama atau pengaturan:

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - File yang dirusak mendapat expected: reject di manifes, dengan kerusakan dicatat di - sampingnya. Dua hal ditolak sebelum apa pun ditulis, karena masing-masing akan menaruh file di - disk yang digambarkan manifes secara keliru: -

    -
      -
    • file yang lebih kecil dari yang dibutuhkan kerusakan, karena akan keluar tanpa perubahan
    • -
    • - expected: accept di samping kerusakan, karena tidak ada yang dapat memenuhinya. Tulis - sanitize bila sistem yang diuji dimaksudkan memperbaiki file, atau - unspecified bila itulah pertanyaan yang Anda ajukan -
    • -
    -

    - Yang ketiga tidak dapat diketahui sebelumnya. Bila suatu kerusakan berjalan dan tidak menggeser satu - byte pun, file itu dibuang alih-alih ditulis - run berlanjut, menyebut file mana itu, dan - berakhir dengan kode keluar parsial. -

    -

    - Langkah demi langkah, dengan tes yang membaca manifes: cara membuat - file rusak untuk pengujian. -

    +
    +

    Halaman dokumentasi

    + {{ template "linkCards" .Docs }}
    -
    -

    Seperti apa bentuk sebuah resep?

    -

    - Resep adalah file YAML yang menggambarkan satu run utuh. Commit di samping pengujian Anda dan - fixture berhenti menjadi biner di repositori Anda - siapa pun dapat membangunnya kembali, byte - demi byte, dari file berisi beberapa ratus karakter. -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - Setiap target memerlukan tepat satu dari size, size-range, - boundary, atau contains. Dua adalah galat dan tidak ada juga galat. - Resep yang tidak valid menulis tidak ada file sama sekali dan melaporkan semua - masalah sekaligus, bukan hanya yang pertama, masing-masing menyebut pengaturan yang dimaksud. -

    +
    +

    Apa yang dilakukan alat ini, per topik

    + {{ template "linkCards" (.PagesOf "formats" "presets" "damage" "samples" "upload-tests" "ci" "exact-size") }}
    -
    -

    Bagaimana menyatakan apa yang harus dilakukan sistem saya terhadap sebuah file?

    -

    Bentuk pendek bila hasilnya sudah cukup, bentuk panjang bila alasannya penting:

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - Hasilnya adalah accept, reject, sanitize, dan - unspecified. Alasannya adalah daftar tertutup agar laporan dapat mengelompokkan - berdasarkan itu: content_malformed, count_limit, - dimensions_limit, duplicate, encoding_invalid, - extension_rule, filename_invalid, filename_too_long, - filename_traversal, malware_signature, mime_mismatch, - nesting_depth, none, size_limit, dan - size_zero. -

    -

    - Alasan menyebut aturan yang berlaku, bukan putusannya. Itulah sebabnya alasan yang - sama dapat berada di bawah kedua hasil - file satu byte di bawah batas adalah - accept, dan aturan yang dimaksud tetap size_limit. -

    -
    - -
    -

    Apa isi manifes?

    -

    - Manifes ditulis di samping file pada akhir setiap run, termasuk run yang terhenti. Satu entri per - file: -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "{{ .Facts.Version }}" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - recipe_hash ditambahkan bila run berasal dari resep, dan preset dengan - overrides bila berasal dari preset, sehingga manifes selalu dapat ditelusuri ke apa - yang menghasilkannya. -

    -

    - Setiap entri juga membawa target_id, id target dalam resep yang menghasilkan file, dan - summary.by_target menghitung file yang dihasilkan tiap target. Resep dengan - beberapa target dapat diperiksa target demi target tanpa membaca nama file. -

    -
    - -
    -

    Apa itu preset?

    -

    - Set file siap pakai yang menjawab pertanyaan pengujian umum, sehingga Anda tidak perlu merancang - setnya sendiri. Preset pada dasarnya resep biasa, dan eject mencetak resepnya agar - dapat Anda sunting dari sana. Setiap preset memiliki halamannya - sendiri berisi apa yang biasanya ditemukan, isi set, dan setiap pengaturan yang diterimanya. -

    - {{ template "presetsList" . }} -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show memberi tahu berapa biaya set sebelum Anda membuatnya, dan menyatakan terus terang - bila sebuah angka adalah nilai sementara dari kami, bukan batas dari Anda. -

    -
    - -
    -

    Apa arti kode keluar?

    -

    - Setiap akhir punya kodenya sendiri, keluaran yang terbaca mesin masuk ke keluaran standar, dan run - yang gagal tidak mencetak apa pun di sana. Tabelnya adalah kontrak beku - mengubah arti sebuah - kode memerlukan kenaikan versi mayor. -

    - {{ template "exitCodesTable" . }} -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - Run yang dihentikan dengan Ctrl+C tetap meninggalkan manifes dan tidak pernah meninggalkan file yang - tertulis setengah, sehingga job yang dibatalkan masih dapat dibersihkan oleh yang berikutnya. -

    -

    - Workflow siap pakai untuk GitHub Actions dan GitLab CI: cara membuat - file uji di pipeline CI. -

    -
    - -
    -

    Apakah ada jendela desktop?

    -

    - Ada, mesin yang sama dengan jendela di atasnya, untuk pengujian yang tidak diskripkan. Ini bukan - versi terpangkas: sebuah pengujian membandingkan kedua antarmuka kemampuan demi kemampuan, dan - apa pun yang hanya dapat dilakukan salah satunya harus dinyatakan dan dibenarkan alih-alih - diam-diam menyimpang. -

    +
    +

    Masih buntu?

    - Layarnya adalah satu batch, preset, beberapa batch sekaligus, dan tentang. Jendela ini menunjukkan - biaya sebuah run sebelum menulis apa pun, melaporkan kemajuan selama berjalan, dan dapat - dibatalkan di tengah jalan tanpa meninggalkan file yang tertulis setengah. Jendela ini belum - membuka file resep - untuk saat ini resep urusan baris perintah, dan jendela membangun batch-nya - di formulir. + tfg <command> --help menunjukkan di terminal apa yang diterima sebuah perintah. Setiap penolakan menyebut pengaturan yang dimaksud, alasannya, dan nilai yang akan berhasil. Jika sesuatu tidak berperilaku seperti yang dikatakan halaman ini, laporkan. Itu kesalahan halaman atau program.

    diff --git a/web/content/id/site.json b/web/content/id/site.json index 3558f0d8..6819ea19 100644 --- a/web/content/id/site.json +++ b/web/content/id/site.json @@ -138,7 +138,8 @@ "colSha256": "SHA-256", "colExpected": "Diharapkan", "colTool": "Alat", - "colQuestion": "Yang dijawabnya" + "colQuestion": "Yang dijawabnya", + "docsMenuLabel": "Halaman dokumentasi" }, "endings": { "0": "Semuanya berjalan.", @@ -386,5 +387,45 @@ "checksum": "Apakah file ini benar file yang diakuinya?", "checksum-check": "Apakah setiap file masih sesuai dengan yang dinyatakan file checksum-nya?", "checksum-write": "Bagaimana nanti saya tahu bahwa tidak satu pun dari file ini berubah?" + }, + "docs": { + "guides": { + "guide-install": { + "title": "Pemasangan", + "text": "Unduh untuk Windows, macOS, atau Linux, periksa arsipnya, atau pasang dengan Docker, npm, pip, atau Go." + }, + "guide-start": { + "title": "Memulai", + "text": "Berkas pertama dengan ukuran tepat, lalu sepuluh ribu, diperiksa, dihapus, dan ditulis sebagai resep." + }, + "guide-commands": { + "title": "Perintah", + "text": "Setiap perintah dan setiap opsi beserta nilai bawaannya, dan semua kode keluar." + }, + "guide-recipes": { + "title": "Menulis resep", + "text": "Setiap kunci resep, ukuran, nama berkas, reaksi yang diharapkan, kerusakan, arsip, dan preset." + }, + "recipes": { + "title": "Galeri resep", + "text": "Resep siap unduh untuk unggahan, impor, arsip, email, media, CI, dan berkas massal." + }, + "guide-manifest": { + "title": "Manifes", + "text": "Setiap bidang manifest.json dan cara tes membacanya." + }, + "guide-formats": { + "title": "Pengaturan format", + "text": "Setiap pengaturan setiap format, dengan nilai yang diterima dan nilai bawaannya." + }, + "guide-frameworks": { + "title": "Framework pengujian", + "text": "Berkas di dalam pytest, Playwright, Vitest, dan node:test." + }, + "guide-window": { + "title": "Aplikasi desktop", + "text": "Jendela program, layar demi layar." + } + } } } diff --git a/web/content/it/docs.html b/web/content/it/docs.html index b898b8a3..53f8c592 100644 --- a/web/content/it/docs.html +++ b/web/content/it/docs.html @@ -1,285 +1,21 @@

    Documentazione

    - Tutto ciò che fa lo strumento, organizzato come le domande con cui le persone arrivano davvero. Il - README nel repository è il riferimento completo e corrisponde - sempre alla build che hai scaricato. + Come installare tfg, creare i primi file di test e tutto ciò che il programma accetta e scrive: ogni comando e ogni opzione, ogni chiave di una ricetta, ogni campo del manifest e ogni impostazione di ogni formato. Queste pagine sono in inglese, perché vengono prodotte dal programma stesso a ogni costruzione del sito, e dicono quindi sempre ciò che fa la versione che scarichi.

    -
    -

    Quali comandi esistono?

    -

    Ognuno fa una cosa sola:

    - {{ template "commandList" . }} -

    - tfg tool raccoglie gli strumenti per i file che hai già, come il controllo di un archivio - prima di decomprimerlo. Strumenti descrive ciascuno di essi. -

    -
    - -
    -

    Come genero un singolo file di dimensione esatta?

    -

    - Indica il formato, la dimensione e la destinazione. Le dimensioni si contano a 1024, quindi - 2mb sono 2097152 byte. Funziona anche un semplice numero di byte, quindi - --size 10485761 chiede esattamente quel numero. -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    Le opzioni utili di generate:

    -
    - - - - - - - - - - - - - - - - - -
    OpzioneCosa fa
    --format <id>formato dei file, per esempio txt
    --size <size>dimensione esatta di ogni file, come 10mb o un semplice numero di byte
    --size-range <a-b>una dimensione estratta per file da un intervallo, come 1kb-8kb. L'estrazione viene dal seed
    --boundary <size>tre file attorno a un limite: un byte sotto, il limite, un byte sopra
    --count <n>quanti file produrre. Predefinito 1
    --name <template>modello del nome, per esempio invoice_{index:04}.txt
    --out <dir>directory in cui scrivere
    --seed <n>seed dell'esecuzione. Lo stesso seed dà gli stessi byte
    --set <k>=<v>un'impostazione di formato, ripetibile
    --damage <name>rompere i file di proposito, ripetibile e applicato in ordine. Esegui tfg damage per l'elenco
    --expected <outcome>accept, reject, sanitize oppure unspecified
    --dry-runcontare e mostrare, senza scrivere assolutamente nulla
    --jsonscrivere il manifest sullo standard output
    -
    -
    - -
    -

    Come faccio un file rotto di proposito?

    -

    - Ogni altro file che questo strumento scrive è corretto per costruzione, il che risponde a due delle - tre domande che pone un validatore di upload. --damage risponde alla terza - il - file si apre, almeno. Il file viene prodotto normalmente e poi rotto, quindi ha ancora la - dimensione che hai chiesto. -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - Le impostazioni vanno dopo i due punti. L'opzione si ripete, e l'ordine in cui le scrivi è l'ordine - in cui vengono applicate. tfg damage elenca cosa può fare questa versione e cosa - accetta ciascuno. -

    -

    In una ricetta la chiave è un elenco, di nomi o di impostazioni:

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - Un file danneggiato riceve expected: reject nel manifest, con il danno registrato - accanto. Due cose vengono rifiutate prima di scrivere qualsiasi cosa, perché ciascuna metterebbe - su disco un file che il manifest descrive in modo sbagliato: -

    -
      -
    • un file più piccolo di quanto serve al danno, perché uscirebbe invariato
    • -
    • - expected: accept accanto a un danno, perché nulla potrebbe soddisfarlo. Scrivi - sanitize se il sistema sotto test deve riparare il file, oppure - unspecified se è proprio la domanda che stai ponendo -
    • -
    -

    - Una terza non si può sapere in anticipo. Se un danno viene eseguito e non sposta alcun byte, quel - file viene scartato invece di essere scritto - l'esecuzione prosegue, dice di quale file si - trattava e termina con il codice di uscita parziale. -

    -

    - Passo dopo passo, con un test che legge il manifest: come - creare un file corrotto per i test. -

    +
    +

    Pagine della documentazione

    + {{ template "linkCards" .Docs }}
    -
    -

    Che aspetto ha una ricetta?

    -

    - Una ricetta è un file YAML che descrive un'intera esecuzione. Committala accanto ai tuoi test e le - fixture smettono di essere binari nel tuo repository - chiunque può ricostruirle, byte per byte, - da un file di poche centinaia di caratteri. -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - Ogni target richiede esattamente una di queste chiavi: size, size-range, - boundary o contains. Due è un errore, e anche nessuna. Una ricetta non - valida scrive nessun file e segnala tutti i problemi insieme invece del solo - primo, ognuno con il nome dell'impostazione a cui si riferisce. -

    +
    +

    Che cosa fa lo strumento, argomento per argomento

    + {{ template "linkCards" (.PagesOf "formats" "presets" "damage" "samples" "upload-tests" "ci" "exact-size") }}
    -
    -

    Come dichiaro cosa deve fare il mio sistema con un file?

    -

    Forma breve quando basta l'esito, forma lunga quando conta il motivo:

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - Gli esiti sono accept, reject, sanitize e - unspecified. I motivi sono un elenco chiuso così un report può raggrupparli: - content_malformed, count_limit, dimensions_limit, - duplicate, encoding_invalid, extension_rule, - filename_invalid, filename_too_long, filename_traversal, - malware_signature, mime_mismatch, nesting_depth, - none, size_limit e size_zero. -

    -

    - Un motivo nomina la regola in gioco, non il verdetto. Ecco perché lo stesso motivo - può stare sotto l'uno o l'altro esito - un file un byte sotto un limite è accept, e - la regola in questione resta size_limit. -

    -
    - -
    -

    Cosa c'è nel manifest?

    -

    - Viene scritto accanto ai file alla fine di ogni esecuzione, compresa un'esecuzione interrotta. Una - voce per file: -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "{{ .Facts.Version }}" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - Un recipe_hash viene aggiunto quando l'esecuzione viene da una ricetta, e - preset con overrides quando viene da un preset, così un manifest si - può sempre ricondurre a ciò che lo ha prodotto. -

    -

    - Ogni voce porta anche target_id, l'id del target della ricetta che ha prodotto il file, - e summary.by_target conta i file a cui è arrivato ciascun target. Una ricetta con - più target si può quindi controllare target per target senza leggere i nomi dei file. -

    -
    - -
    -

    Cos'è un preset?

    -

    - Un set di file pronto che risponde a una domanda di test comune, così non devi progettare il set tu. - I preset sono ricette ordinarie sotto il cofano, e eject stampa la ricetta così - puoi modificarla da lì. Ogni preset ha una pagina tutta sua con cosa - trova di solito, cosa c'è nel set e ogni impostazione che accetta. -

    - {{ template "presetsList" . }} -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show ti dice quanto costerebbe il set prima di costruirlo, e dice apertamente quando un - numero è un segnaposto nostro anziché un limite tuo. -

    -
    - -
    -

    Cosa significano i codici di uscita?

    -

    - Ogni conclusione ha il suo codice, l'output leggibile da macchina va sullo standard output, e - un'esecuzione fallita non vi stampa nulla. La tabella è un contratto congelato - cambiare il - significato di un codice richiede una versione maggiore. -

    - {{ template "exitCodesTable" . }} -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - Un'esecuzione fermata con Ctrl+C lascia comunque un manifest e non lascia mai un file scritto a - metà, così un job annullato può ancora essere ripulito dal successivo. -

    -

    - Workflow pronti per GitHub Actions e GitLab CI: come generare file - di test in una pipeline CI. -

    -
    - -
    -

    Esiste una finestra desktop?

    -

    - Sì, lo stesso motore con una finestra sopra, per il test che non è automatizzato. Non è una versione - ridotta: un test confronta le due interfacce capacità per capacità, e tutto ciò che può fare - solo una delle due va dichiarato e giustificato invece di divergere in silenzio. -

    +
    +

    Ancora bloccato?

    - Le schermate sono un lotto, i preset, più lotti insieme e Informazioni. Mostra quanto costerebbe - un'esecuzione prima di scrivere qualsiasi cosa, riporta l'avanzamento mentre gira e si può - annullare a metà senza lasciare un file scritto a metà. Non apre ancora un file di ricetta - per - ora le ricette sono una faccenda da riga di comando, e la finestra costruisce i suoi lotti nel - modulo. + tfg <command> --help mostra nel terminale che cosa accetta un comando. Ogni rifiuto nomina l'impostazione a cui si riferisce, il motivo e un valore che funzionerebbe. Se qualcosa non si comporta come dice una pagina, segnalalo. È un errore della pagina o del programma.

    diff --git a/web/content/it/site.json b/web/content/it/site.json index bf170c48..d390b06a 100644 --- a/web/content/it/site.json +++ b/web/content/it/site.json @@ -138,7 +138,8 @@ "colSha256": "SHA-256", "colExpected": "Atteso", "colTool": "Strumento", - "colQuestion": "A cosa risponde" + "colQuestion": "A cosa risponde", + "docsMenuLabel": "Pagine della documentazione" }, "endings": { "0": "Tutto ha funzionato.", @@ -386,5 +387,45 @@ "checksum": "Questo file è davvero quello che dichiara di essere?", "checksum-check": "Ogni file è ancora come dice il suo file di checksum?", "checksum-write": "Come saprò più tardi che nessuno di questi file è cambiato?" + }, + "docs": { + "guides": { + "guide-install": { + "title": "Installazione", + "text": "Scaricare per Windows, macOS o Linux, verificare l'archivio o installare con Docker, npm, pip o Go." + }, + "guide-start": { + "title": "Primi passi", + "text": "Un primo file di dimensione esatta, poi diecimila, verificati, rimossi e scritti come ricetta." + }, + "guide-commands": { + "title": "Comandi", + "text": "Ogni comando e ogni opzione con il valore predefinito, e tutti i codici di uscita." + }, + "guide-recipes": { + "title": "Scrivere ricette", + "text": "Ogni chiave di una ricetta, dimensioni, nomi dei file, reazioni attese, danni, archivi e preset." + }, + "recipes": { + "title": "Raccolta di ricette", + "text": "Ricette pronte da scaricare per upload, importazioni, archivi, email, contenuti multimediali, CI e file in massa." + }, + "guide-manifest": { + "title": "Manifest", + "text": "Ogni campo di manifest.json e come lo legge un test." + }, + "guide-formats": { + "title": "Impostazioni dei formati", + "text": "Ogni impostazione di ogni formato, con i valori accettati e il valore predefinito." + }, + "guide-frameworks": { + "title": "Framework di test", + "text": "I file dentro pytest, Playwright, Vitest e node:test." + }, + "guide-window": { + "title": "Applicazione desktop", + "text": "La finestra, schermata per schermata." + } + } } } diff --git a/web/content/ja/docs.html b/web/content/ja/docs.html index 70dc7341..62f169ed 100644 --- a/web/content/ja/docs.html +++ b/web/content/ja/docs.html @@ -1,239 +1,21 @@

    ドキュメント

    - ツールの機能を、実際に寄せられる質問の形で整理しています。リポジトリのREADMEが完全なリファレンスで、ダウンロードしたビルドと常に一致しています。 + tfg のインストール、最初のテストファイルの作成、そしてプログラムが受け取り書き出すすべて。すべてのコマンドとフラグ、レシピのすべてのキー、マニフェストのすべてのフィールド、すべての形式のすべての設定です。これらのページは英語です。サイトを作るたびにプログラム自身から生成されるので、ダウンロードするバージョンの動作と常に一致します。

    -
    -

    どんなコマンドがありますか。

    -

    それぞれが1つのことだけを行います。

    - {{ template "commandList" . }} -

    - tfg toolには、展開前のアーカイブの検査など、手元にあるファイル向けのツールがあります。それぞれの説明はツールにあります。 -

    -
    - -
    -

    正確なサイズのファイルを1つ生成するには。

    -

    - 形式、サイズ、出力先を指定します。サイズは1024単位で数えるため、2mbは2097152バイトです。バイト数をそのまま指定することもでき、--size - 10485761はちょうどその数のバイトを要求します。 -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    generateで便利なフラグ:

    -
    - - - - - - - - - - - - - - - - - -
    フラグ動作
    --format <id>ファイルの形式。例:txt
    --size <size>各ファイルの正確なサイズ。10mbのような指定、またはバイト数
    --size-range <a-b>範囲からファイルごとに決めるサイズ。例:1kb-8kb。抽選はシードから決まります
    --boundary <size>制限の前後の3ファイル。1バイト下、制限値ちょうど、1バイト上
    --count <n>作成するファイル数。既定は1
    --name <template>名前のテンプレート。例:invoice_{index:04}.txt
    --out <dir>書き込み先のディレクトリ
    --seed <n>実行のシード。同じシードなら同じバイトになります
    --set <k>=<v>形式の設定。繰り返し指定できます
    --damage <name>ファイルを意図的に壊します。繰り返し指定でき、順番に適用されます。一覧はtfg damageで確認できます
    --expected <outcome>accept、reject、sanitize、unspecified
    --dry-run数えて表示するだけで、何も書き込みません
    --jsonマニフェストを標準出力に書き出します
    -
    -
    - -
    -

    意図的に壊れたファイルを作るには。

    -

    - このツールが書き込むそれ以外のファイルは、構造上すべて正しく、アップロード検証が問う3つの疑問のうち2つに答えます。--damageは3つ目、つまりファイルがそもそも開けるかに答えます。ファイルは通常どおり生成されてから壊されるため、要求したサイズのままです。 -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - 設定はコロンの後ろに書きます。フラグは繰り返せて、書いた順に適用されます。tfg damageは、このビルドで何ができるか、それぞれが何を受け付けるかを一覧表示します。 -

    -

    レシピでは、キーは名前または設定のリストになります。

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - 壊されたファイルには、マニフェストでexpected: - rejectが付き、横に壊した内容が記録されます。次の2つは、何かを書き込む前に拒否されます。どちらもマニフェストの記述と食い違うファイルをディスクに残してしまうためです。 -

    -
      -
    • 破壊に必要なサイズより小さいファイル。変更されないまま出てきてしまうため
    • -
    • - 破壊と併記されたexpected: - accept。どのファイルもそれを満たせないためです。テスト対象のシステムがファイルを修復する想定ならsanitizeを、まさにそれが調べたい点ならunspecifiedを書いてください -
    • -
    -

    - 3つ目は事前には分かりません。破壊が実行されても1バイトも変わらなかった場合、そのファイルは書き込まれずに破棄されます。実行は続き、どのファイルだったかを伝え、一部のみ完了した終了コードで終わります。 -

    -

    - 手順を追って、マニフェストを読むテストつきで説明します。テスト用の破損ファイルを作る方法。 -

    +
    +

    ドキュメントのページ

    + {{ template "linkCards" .Docs }}
    -
    -

    レシピはどんな見た目ですか。

    -

    - レシピは、実行全体を記述するYAMLファイルです。テストの隣にコミットすれば、フィクスチャはリポジトリ内のバイナリではなくなります。数百文字のファイルから、誰でもバイト単位で再構築できます。 -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - 各ターゲットには、size、size-range、boundary、containsのうち、ちょうど1つが必要です。2つはエラーで、ゼロもエラーです。無効なレシピはファイルを1つも書き込まず、最初の問題だけでなくすべての問題をまとめて報告し、それぞれ該当する設定名を示します。 -

    +
    +

    このツールでできること、テーマ別

    + {{ template "linkCards" (.PagesOf "formats" "presets" "damage" "samples" "upload-tests" "ci" "exact-size") }}
    -
    -

    システムがファイルをどう扱うべきかを宣言するには。

    -

    結果だけで足りるなら短い形式を、理由が重要なら長い形式を使います。

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - 結果はaccept、reject、sanitize、unspecifiedです。理由は閉じたリストで、レポートで理由ごとにグループ化できます。content_malformed、count_limit、dimensions_limit、duplicate、encoding_invalid、extension_rule、filename_invalid、filename_too_long、filename_traversal、malware_signature、mime_mismatch、nesting_depth、none、size_limit、size_zero。 -

    -

    - 理由が示すのは判定ではなく問題になっているルールです。そのため、同じ理由が両方の結果の下に現れることがあります。制限より1バイト小さいファイルはacceptですが、対象となるルールは依然としてsize_limitです。 -

    -
    - -
    -

    マニフェストには何が入っていますか。

    -

    - 中断された実行も含め、すべての実行の終了時にファイルの隣へ書き出されます。ファイルごとに1項目です。 -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "{{ .Facts.Version }}" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - 実行がレシピから来た場合はrecipe_hashが、プリセットから来た場合はpresetとoverridesが追加されるため、マニフェストは常に生成元までたどれます。 -

    -

    - 各項目には、ファイルを生成したレシピ内のターゲットのIDであるtarget_idも入り、summary.by_targetが各ターゲットのファイル数を数えます。複数のターゲットを持つレシピも、ファイル名を読まずにターゲットごとに確認できます。 -

    -
    - -
    -

    プリセットとは何ですか。

    -

    - 一般的なテストの疑問に答える既製のファイルセットで、セットを自分で設計する必要がありません。プリセットの中身は普通のレシピで、ejectがそのレシピを出力するので、そこから編集できます。各プリセットには、普通は何を見つけるか、セットの内容、受け付ける設定をまとめた専用ページがあります。 -

    - {{ template "presetsList" . }} -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - showは、セットを作る前にかかるコストを伝え、数値があなたの制限ではなくこちらの仮の値である場合は、はっきりそう伝えます。 -

    -
    - -
    -

    終了コードは何を意味しますか。

    -

    - 終わり方ごとに専用のコードがあり、機械可読な出力は標準出力に出て、失敗した実行はそこに何も出力しません。この表は凍結された契約で、コードの意味を変えるにはメジャーバージョンを上げる必要があります。 -

    - {{ template "exitCodesTable" . }} -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - Ctrl+Cで止めた実行でも、マニフェストは残り、書きかけのファイルは決して残りません。そのため、キャンセルされたジョブも次のジョブが片付けられます。 -

    -

    - GitHub ActionsとGitLab CI向けのすぐ使えるワークフロー。CIパイプラインでテストファイルを生成する方法。 -

    -
    - -
    -

    デスクトップウィンドウはありますか。

    -

    - はい。同じエンジンにウィンドウを載せたもので、スクリプト化しないテスト向けです。機能削減版ではありません。テストが2つのインターフェースを機能ごとに比較しており、片方にしかできないことは、静かに食い違うのではなく、宣言して理由を示す必要があります。 -

    +
    +

    まだ解決しませんか?

    - 画面は、単一バッチ、プリセット、複数バッチ同時、バージョン情報です。書き込む前に実行のコストを表示し、実行中は進捗を報告し、途中でキャンセルしても書きかけのファイルは残りません。レシピファイルはまだ開けません。レシピは今のところコマンドラインのもので、ウィンドウはフォームでバッチを組み立てます。 + tfg <command> --help を使うと、コマンドが受け取るものがターミナルに表示されます。拒否されたときは、どの設定についてか、その理由、そして使える値が必ず示されます。ページの説明どおりに動かない場合は 報告してください。それはページかプログラムの不具合です。

    diff --git a/web/content/ja/site.json b/web/content/ja/site.json index 12537d58..d48ed364 100644 --- a/web/content/ja/site.json +++ b/web/content/ja/site.json @@ -138,7 +138,8 @@ "colSha256": "SHA-256", "colExpected": "期待される結果", "colTool": "ツール", - "colQuestion": "答える問い" + "colQuestion": "答える問い", + "docsMenuLabel": "ドキュメントのページ" }, "endings": { "0": "すべて正常に動作しました。", @@ -386,5 +387,45 @@ "checksum": "このファイルは、名乗っているとおりのファイルでしょうか。", "checksum-check": "どのファイルも、チェックサムファイルに書かれたとおりのままでしょうか。", "checksum-write": "これらのファイルがどれも変わっていないことを、後でどう確かめればよいでしょうか。" + }, + "docs": { + "guides": { + "guide-install": { + "title": "インストール", + "text": "Windows、macOS、Linux 用をダウンロードしてアーカイブを確認するか、Docker、npm、pip、Go でインストールします。" + }, + "guide-start": { + "title": "はじめに", + "text": "正確なサイズの最初のファイル、次に一万個のファイルを作り、確認し、削除し、レシピとして書き残します。" + }, + "guide-commands": { + "title": "コマンド", + "text": "すべてのコマンドとすべてのフラグ、その既定値、そしてすべての終了コード。" + }, + "guide-recipes": { + "title": "レシピの書き方", + "text": "レシピのすべてのキー、サイズ、ファイル名、期待される反応、破損、アーカイブ、プリセット。" + }, + "recipes": { + "title": "レシピ集", + "text": "アップロード、インポート、アーカイブ、メール、メディア、CI、大量ファイル向けの、ダウンロードしてすぐ使えるレシピ。" + }, + "guide-manifest": { + "title": "マニフェスト", + "text": "manifest.json のすべてのフィールドと、テストでの読み方。" + }, + "guide-formats": { + "title": "形式の設定", + "text": "すべての形式のすべての設定と、受け付ける値、既定値。" + }, + "guide-frameworks": { + "title": "テストフレームワーク", + "text": "pytest、Playwright、Vitest、node:test の中でファイルを使う方法。" + }, + "guide-window": { + "title": "デスクトップアプリ", + "text": "ウィンドウを画面ごとに説明します。" + } + } } } diff --git a/web/content/ko/docs.html b/web/content/ko/docs.html index 76bacb18..b33c01d8 100644 --- a/web/content/ko/docs.html +++ b/web/content/ko/docs.html @@ -1,260 +1,21 @@

    문서

    - 도구가 하는 모든 일을 사람들이 실제로 가져오는 질문 형태로 정리했습니다. 저장소의 README가 전체 레퍼런스이며, - 내려받은 빌드와 항상 일치합니다. + tfg 설치 방법, 첫 테스트 파일 만들기, 그리고 프로그램이 받고 쓰는 모든 것. 모든 명령과 플래그, 레시피의 모든 키, 매니페스트의 모든 필드, 모든 형식의 모든 설정을 다룹니다. 이 페이지들은 영어로 되어 있습니다. 사이트를 만들 때마다 프로그램 자체에서 생성되므로 내려받는 버전이 하는 일과 항상 일치합니다.

    -
    -

    어떤 명령이 있나요?

    -

    각 명령은 한 가지 일만 합니다.

    - {{ template "commandList" . }} -

    - tfg tool에는 압축을 풀기 전에 아카이브를 검사하는 것처럼 이미 가진 파일을 위한 도구가 들어 있습니다. 각 도구는 도구에서 설명합니다. -

    -
    - -
    -

    정확한 크기의 파일 하나는 어떻게 만드나요?

    -

    - 형식, 크기, 저장 위치를 지정합니다. 크기는 1024 단위로 세므로 2mb는 2097152바이트입니다. 바이트 수를 그대로 써도 되므로 - --size 10485761은 정확히 그만큼을 요청합니다. -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    generate에서 유용한 플래그:

    -
    - - - - - - - - - - - - - - - - - -
    플래그동작
    --format <id>파일의 형식. 예: txt
    --size <size>각 파일의 정확한 크기. 10mb와 같은 값 또는 바이트 수
    --size-range <a-b>범위에서 파일마다 뽑는 크기. 예: 1kb-8kb. 추첨은 시드에서 나옵니다
    --boundary <size>한도 주변의 파일 세 개: 1바이트 아래, 한도 값, 1바이트 위
    --count <n>만들 파일 수. 기본값은 1
    --name <template>이름 템플릿. 예: invoice_{index:04}.txt
    --out <dir>쓸 디렉터리
    --seed <n>실행의 시드. 같은 시드는 같은 바이트를 만듭니다
    --set <k>=<v>형식 설정, 여러 번 지정할 수 있음
    --damage <name>파일을 일부러 망가뜨립니다. 여러 번 지정할 수 있으며 순서대로 적용됩니다. 목록은 tfg damage로 봅니다
    --expected <outcome>accept, reject, sanitize, unspecified
    --dry-run세어서 보여 주기만 하고 아무것도 쓰지 않음
    --json매니페스트를 표준 출력에 씀
    -
    -
    - -
    -

    일부러 망가진 파일은 어떻게 만드나요?

    -

    - 이 도구가 쓰는 다른 모든 파일은 구조상 올바르며, 이는 업로드 검증기가 던지는 세 가지 질문 중 두 가지에 답합니다. --damage는 세 번째, 곧 - 파일이 아예 열리는지에 답합니다. 파일은 정상적으로 만들어진 뒤 망가지므로 요청한 크기는 그대로입니다. -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - 설정은 콜론 뒤에 씁니다. 플래그는 반복할 수 있으며, 쓴 순서가 적용 순서입니다. tfg damage는 이 빌드가 할 수 있는 것과 각각이 받는 값을 - 나열합니다. -

    -

    레시피에서는 키가 이름 또는 설정의 목록입니다.

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - 손상된 파일은 매니페스트에서 expected: reject를 받고, 옆에 손상 내용이 기록됩니다. 두 가지는 아무것도 쓰기 전에 거부됩니다. 각각 - 매니페스트가 잘못 설명하는 파일을 디스크에 남기게 되기 때문입니다. -

    -
      -
    • 손상에 필요한 크기보다 작은 파일. 바뀌지 않은 채 나오기 때문입니다
    • -
    • - 손상과 함께 쓴 expected: accept. 어떤 파일도 이를 충족할 수 없기 때문입니다. 테스트 대상 시스템이 파일을 복구해야 한다면 - sanitize를, 바로 그것이 묻고 싶은 질문이라면 unspecified를 쓰세요 -
    • -
    -

    - 세 번째는 미리 알 수 없습니다. 손상이 실행되었는데 한 바이트도 바뀌지 않았다면 그 파일은 쓰이지 않고 버려집니다. 실행은 계속되고, 어떤 파일이었는지 알려 주며, 일부만 완료된 - 종료 코드로 끝납니다. -

    -

    - 단계별로, 매니페스트를 읽는 테스트와 함께 설명합니다. 테스트용 손상 파일을 만드는 방법. -

    +
    +

    문서 페이지

    + {{ template "linkCards" .Docs }}
    -
    -

    레시피는 어떻게 생겼나요?

    -

    - 레시피는 실행 전체를 기술하는 YAML 파일입니다. 테스트 옆에 커밋하면 픽스처는 더 이상 저장소의 바이너리가 아닙니다. 몇백 자짜리 파일만 있으면 누구나 바이트 단위로 똑같이 - 다시 만들 수 있습니다. -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - 각 타깃에는 size, size-range, boundary, contains 중 - 정확히 하나가 필요합니다. 둘은 오류이고 하나도 없는 것도 오류입니다. 올바르지 않은 레시피는 파일을 하나도 쓰지 않으며, 첫 번째 문제만이 - 아니라 모든 문제를 한꺼번에 보고하고 각각 해당 설정의 이름을 알려 줍니다. -

    +
    +

    이 도구가 하는 일, 주제별

    + {{ template "linkCards" (.PagesOf "formats" "presets" "damage" "samples" "upload-tests" "ci" "exact-size") }}
    -
    -

    시스템이 파일을 어떻게 처리해야 하는지는 어떻게 선언하나요?

    -

    결과만 있으면 충분할 때는 짧은 형식을, 이유가 중요할 때는 긴 형식을 씁니다.

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - 결과는 accept, reject, sanitize, unspecified입니다. - 이유는 닫힌 목록이라 보고서가 이유별로 묶을 수 있습니다. content_malformed, count_limit, - dimensions_limit, duplicate, encoding_invalid, - extension_rule, filename_invalid, filename_too_long, - filename_traversal, malware_signature, mime_mismatch, - nesting_depth, none, size_limit, size_zero. -

    -

    - 이유가 가리키는 것은 판정이 아니라 문제가 되는 규칙입니다. 그래서 같은 이유가 어느 결과 아래에도 올 수 있습니다. 한도보다 1바이트 작은 파일은 - accept이지만, 관련된 규칙은 여전히 size_limit입니다. -

    -
    - -
    -

    매니페스트에는 무엇이 들어 있나요?

    -

    - 중단된 실행을 포함해 모든 실행이 끝날 때 파일 옆에 쓰입니다. 파일마다 항목이 하나씩 있습니다. -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "{{ .Facts.Version }}" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - 실행이 레시피에서 왔다면 recipe_hash가, 프리셋에서 왔다면 preset과 overrides가 - 추가되므로, 매니페스트는 항상 그것을 만든 출처까지 추적할 수 있습니다. -

    -

    - 각 항목에는 파일을 만든 레시피 타깃의 id인 target_id도 들어 있고, summary.by_target은 각 타깃이 만든 파일 - 수를 셉니다. 따라서 타깃이 여러 개인 레시피도 파일 이름을 읽지 않고 타깃별로 확인할 수 있습니다. -

    -
    - -
    -

    프리셋이란 무엇인가요?

    -

    - 흔한 테스트 질문에 답하는 기성 파일 세트로, 세트를 직접 설계할 필요가 없습니다. 프리셋은 내부적으로 평범한 레시피이며, eject가 레시피를 출력하므로 - 거기서부터 편집할 수 있습니다. 각 프리셋에는 보통 무엇을 찾아내는지, 세트에 무엇이 들어 있는지, 어떤 설정을 받는지 설명하는 - 전용 페이지가 있습니다. -

    - {{ template "presetsList" . }} -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show는 세트를 만들기 전에 비용이 얼마나 드는지 알려 주고, 숫자가 여러분의 한도가 아니라 우리 쪽의 임시값일 때는 분명히 말해 줍니다. -

    -
    - -
    -

    종료 코드는 무엇을 뜻하나요?

    -

    - 끝나는 방식마다 고유한 코드가 있고, 기계가 읽을 수 있는 출력은 표준 출력으로 나가며, 실패한 실행은 거기에 아무것도 출력하지 않습니다. 이 표는 고정된 약속이며, 코드의 의미를 - 바꾸려면 메이저 버전을 올려야 합니다. -

    - {{ template "exitCodesTable" . }} -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - Ctrl+C로 멈춘 실행도 매니페스트는 남기고, 쓰다 만 파일은 절대 남기지 않으므로, 취소된 작업을 다음 작업이 정리할 수 있습니다. -

    -

    - GitHub Actions와 GitLab CI용으로 바로 쓸 수 있는 워크플로. CI 파이프라인에서 테스트 파일을 생성하는 - 방법. -

    -
    - -
    -

    데스크톱 창이 있나요?

    -

    - 네. 같은 엔진 위에 창을 얹은 것으로, 스크립트로 하지 않는 테스트를 위한 것입니다. 축소판이 아닙니다. 테스트가 두 인터페이스를 기능별로 비교하며, 한쪽만 할 수 있는 것은 - 조용히 벌어지는 대신 선언하고 이유를 밝혀야 합니다. -

    +
    +

    아직 막히셨나요?

    - 화면은 단일 배치, 프리셋, 여러 배치 동시 실행, 정보입니다. 무엇이든 쓰기 전에 실행 비용을 보여 주고, 실행 중에는 진행 상황을 알려 주며, 쓰다 만 파일을 남기지 않고 - 도중에 취소할 수 있습니다. 아직 레시피 파일은 열지 못합니다. 지금은 레시피가 명령줄의 몫이고, 창은 양식에서 배치를 구성합니다. + tfg <command> --help 명령은 터미널에서 해당 명령이 받는 값을 보여 줍니다. 거부될 때는 항상 어떤 설정 때문인지, 이유, 그리고 사용할 수 있는 값을 알려 줍니다. 페이지 설명과 다르게 동작하면 알려 주세요. 그것은 페이지나 프로그램의 버그입니다.

    diff --git a/web/content/ko/site.json b/web/content/ko/site.json index 431a3c37..019f68a7 100644 --- a/web/content/ko/site.json +++ b/web/content/ko/site.json @@ -138,7 +138,8 @@ "colSha256": "SHA-256", "colExpected": "기대 결과", "colTool": "도구", - "colQuestion": "답하는 질문" + "colQuestion": "답하는 질문", + "docsMenuLabel": "문서 페이지" }, "endings": { "0": "모두 정상적으로 동작했습니다.", @@ -386,5 +387,45 @@ "checksum": "이 파일이 주장하는 바로 그 파일일까요?", "checksum-check": "모든 파일이 아직 체크섬 파일에 적힌 그대로일까요?", "checksum-write": "이 파일들 중 어느 것도 바뀌지 않았다는 것을 나중에 어떻게 알 수 있을까요?" + }, + "docs": { + "guides": { + "guide-install": { + "title": "설치", + "text": "Windows, macOS, Linux용으로 내려받고 압축 파일을 확인하거나 Docker, npm, pip, Go로 설치합니다." + }, + "guide-start": { + "title": "시작하기", + "text": "정확한 크기의 첫 파일, 이어서 만 개의 파일을 만들고 확인하고 지운 뒤 레시피로 남깁니다." + }, + "guide-commands": { + "title": "명령", + "text": "모든 명령과 모든 플래그, 그 기본값, 그리고 모든 종료 코드." + }, + "guide-recipes": { + "title": "레시피 작성", + "text": "레시피의 모든 키, 크기, 파일 이름, 기대 반응, 손상, 압축 파일, 프리셋." + }, + "recipes": { + "title": "레시피 모음", + "text": "업로드, 가져오기, 압축 파일, 이메일, 미디어, CI, 대량 파일을 위해 바로 내려받을 수 있는 레시피." + }, + "guide-manifest": { + "title": "매니페스트", + "text": "manifest.json의 모든 필드와 테스트에서 읽는 방법." + }, + "guide-formats": { + "title": "형식 설정", + "text": "모든 형식의 모든 설정과 허용되는 값, 기본값." + }, + "guide-frameworks": { + "title": "테스트 프레임워크", + "text": "pytest, Playwright, Vitest, node:test 안에서 파일을 쓰는 방법." + }, + "guide-window": { + "title": "데스크톱 앱", + "text": "프로그램 창을 화면별로 설명합니다." + } + } } } diff --git a/web/content/nl/docs.html b/web/content/nl/docs.html index cb8fdc22..c40674e9 100644 --- a/web/content/nl/docs.html +++ b/web/content/nl/docs.html @@ -1,289 +1,21 @@

    Documentatie

    - Alles wat de tool doet, geordend als de vragen waarmee mensen echt komen. De - README in de repository is de volledige referentie en komt altijd - overeen met de build die je hebt gedownload. + Hoe u tfg installeert, uw eerste testbestanden maakt, en alles wat het programma aanneemt en schrijft: elke opdracht en elke optie, elke sleutel van een recept, elk veld van het manifest en elke instelling van elk formaat. Deze pagina's zijn in het Engels, omdat ze bij elke bouw van de site uit het programma zelf ontstaan en dus altijd zeggen wat de versie doet die u downloadt.

    -
    -

    Welke opdrachten zijn er?

    -

    Elke doet precies één ding:

    - {{ template "commandList" . }} -

    - tfg tool bevat de hulpmiddelen voor bestanden die je al hebt, zoals een archief - controleren voordat je het uitpakt. Hulpmiddelen beschrijft elk ervan. -

    -
    - -
    -

    Hoe genereer ik één bestand van een exacte grootte?

    -

    - Noem het formaat, de grootte en waar het naartoe moet. Groottes tellen in 1024-tallen, dus - 2mb is 2097152 bytes. Een gewoon aantal bytes werkt ook, dus --size - 10485761 vraagt precies zoveel. -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    De nuttige opties van generate:

    -
    - - - - - - - - - - - - - - - - - -
    OptieWat het doet
    --format <id>formaat van de bestanden, bijvoorbeeld txt
    --size <size>exacte grootte van elk bestand, zoals 10mb of een gewoon aantal bytes
    --size-range <a-b>een grootte die per bestand uit een bereik wordt getrokken, zoals 1kb-8kb. De trekking komt uit de seed
    --boundary <size>drie bestanden rond een limiet: één byte eronder, de limiet, één byte erboven
    --count <n>hoeveel bestanden te maken. Standaard 1
    --name <template>naamsjabloon, bijvoorbeeld invoice_{index:04}.txt
    --out <dir>map om naartoe te schrijven
    --seed <n>seed van de run. Dezelfde seed geeft dezelfde bytes
    --set <k>=<v>een formaatinstelling, herhaalbaar
    --damage <name>de bestanden met opzet beschadigen, herhaalbaar en in volgorde toegepast. Draai tfg damage voor de lijst
    --expected <outcome>accept, reject, sanitize of unspecified
    --dry-runtellen en tonen, helemaal niets schrijven
    --jsonhet manifest naar de standaarduitvoer schrijven
    -
    -
    - -
    -

    Hoe maak ik een bestand dat met opzet kapot is?

    -

    - Elk ander bestand dat deze tool schrijft is correct per constructie, wat twee van de drie vragen - beantwoordt die een uploadvalidator stelt. --damage beantwoordt de derde - gaat het - bestand überhaupt open. Het bestand wordt normaal gemaakt en daarna beschadigd, dus het heeft - nog steeds de grootte die je vroeg. -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - Instellingen komen na een dubbele punt. De optie herhaalt zich, en de volgorde waarin je ze schrijft - is de volgorde waarin ze worden toegepast. tfg damage toont wat deze build kan en - wat elke variant accepteert. -

    -

    In een recept is de sleutel een lijst, van namen of van instellingen:

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - Een beschadigd bestand krijgt expected: reject in het manifest, met de beschadiging - ernaast vastgelegd. Twee dingen worden geweigerd voordat er iets wordt geschreven, omdat elk - anders een bestand op schijf zou zetten dat het manifest verkeerd beschrijft: -

    -
      -
    • een bestand dat kleiner is dan de beschadiging nodig heeft, omdat het ongewijzigd zou uitkomen
    • -
    • - expected: accept naast een beschadiging, omdat niets daaraan kan voldoen. Schrijf - sanitize als het geteste systeem het bestand moet repareren, of - unspecified als dat de vraag is die je stelt -
    • -
    -

    - Een derde is vooraf niet te weten. Als een beschadiging draait en geen enkele byte verschuift, wordt - dat bestand weggegooid in plaats van geschreven - de run gaat door, zegt om welk bestand het - ging en eindigt met de gedeeltelijke afsluitcode. -

    -

    - Stap voor stap, met een test die het manifest leest: hoe - maak je een beschadigd bestand om mee te testen. -

    +
    +

    Pagina's van de documentatie

    + {{ template "linkCards" .Docs }}
    -
    -

    Hoe ziet een recept eruit?

    -

    - Een recept is een YAML-bestand dat een hele run beschrijft. Commit het naast je tests en de fixtures - zijn geen binaries meer in je repository - iedereen kan ze byte voor byte opnieuw opbouwen uit - een bestand van een paar honderd tekens. -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - Elk target heeft precies één van deze sleutels nodig: size, size-range, - boundary of contains. Twee is een fout en geen ook. Een ongeldig - recept schrijft helemaal geen bestanden en meldt alle problemen tegelijk in - plaats van alleen het eerste, elk met de instelling waar het over gaat. -

    +
    +

    Wat het hulpmiddel doet, per onderwerp

    + {{ template "linkCards" (.PagesOf "formats" "presets" "damage" "samples" "upload-tests" "ci" "exact-size") }}
    -
    -

    Hoe leg ik vast wat mijn systeem met een bestand moet doen?

    -

    Korte vorm als de uitkomst genoeg is, lange vorm als de reden ertoe doet:

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - De uitkomsten zijn accept, reject, sanitize en - unspecified. De redenen zijn een gesloten lijst zodat een rapport erop kan - groeperen: content_malformed, count_limit, - dimensions_limit, duplicate, encoding_invalid, - extension_rule, filename_invalid, filename_too_long, - filename_traversal, malware_signature, mime_mismatch, - nesting_depth, none, size_limit en - size_zero. -

    -

    - Een reden noemt de regel die in het spel is, niet het oordeel. Daarom kan dezelfde - reden onder beide uitkomsten staan - een bestand één byte onder een limiet is - accept, en de regel waar het om gaat is nog steeds size_limit. -

    -
    - -
    -

    Wat staat er in het manifest?

    -

    - Het wordt aan het einde van elke run naast de bestanden geschreven, ook bij een onderbroken run. Eén - item per bestand: -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "{{ .Facts.Version }}" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - Er komt een recipe_hash bij als de run uit een recept kwam, en preset met - overrides als hij uit een preset kwam, zodat een manifest altijd te herleiden is - tot wat het maakte. -

    -

    - Elk item draagt ook target_id, de id van het target in het recept dat het bestand - maakte, en summary.by_target telt de bestanden waar elk target op uitkwam. Een - recept met meerdere targets kan zo target voor target worden gecontroleerd zonder bestandsnamen - te lezen. -

    -
    - -
    -

    Wat is een preset?

    -

    - Een kant-en-klare set bestanden die een veelvoorkomende testvraag beantwoordt, zodat je de set niet - zelf hoeft te ontwerpen. Presets zijn gewone recepten onder de motorkap, en eject - drukt het recept af zodat je het vanaf daar kunt bewerken. Elke preset heeft - een eigen pagina met wat hij meestal vindt, wat er in de set zit en - welke instellingen hij kent. -

    - {{ template "presetsList" . }} -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show zegt je wat de set zou kosten voordat je hem bouwt, en zegt zonder omwegen wanneer - een getal een tijdelijke waarde van ons is in plaats van een limiet van jou. -

    -
    - -
    -

    Wat betekenen de afsluitcodes?

    -

    - Elk einde heeft zijn eigen code, machineleesbare uitvoer gaat naar de standaarduitvoer, en een - mislukte run drukt daar niets af. De tabel is een bevroren contract - de betekenis van een code - wijzigen vereist een major-versie. -

    - {{ template "exitCodesTable" . }} -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - Een run die met Ctrl+C is gestopt laat nog steeds een manifest achter en nooit een half geschreven - bestand, zodat een afgebroken taak door de volgende nog kan worden opgeruimd. -

    -

    - Kant-en-klare workflows voor GitHub Actions en GitLab CI: hoe - genereer je testbestanden in een CI-pipeline. -

    -
    - -
    -

    Is er een bureaubladvenster?

    -

    - Ja, dezelfde engine met een venster erop, voor het testen dat niet geautomatiseerd is. Het is geen - uitgeklede versie: een test vergelijkt de twee interfaces mogelijkheid voor mogelijkheid, en - alles wat maar één van beide kan moet worden verklaard en gerechtvaardigd in plaats van - ongemerkt uit elkaar te drijven. -

    +
    +

    Komt u er nog niet uit?

    - De schermen zijn één batch, presets, meerdere batches tegelijk en info. Het toont wat een run zou - kosten voordat er iets wordt geschreven, meldt de voortgang terwijl het draait en kan halverwege - worden afgebroken zonder een half geschreven bestand achter te laten. Het opent nog geen - receptbestand - recepten zijn voorlopig iets van de opdrachtregel, en het venster bouwt zijn - batches in het formulier. + tfg <command> --help toont in de terminal wat een opdracht aanneemt. Elke weigering noemt de instelling waar het om gaat, de reden en een waarde die wel werkt. Als iets anders werkt dan een pagina hier zegt, meld het. Dan zit de fout in de pagina of in het programma.

    diff --git a/web/content/nl/site.json b/web/content/nl/site.json index 32725759..9a09be47 100644 --- a/web/content/nl/site.json +++ b/web/content/nl/site.json @@ -138,7 +138,8 @@ "colSha256": "SHA-256", "colExpected": "Verwacht", "colTool": "Hulpmiddel", - "colQuestion": "Wat het beantwoordt" + "colQuestion": "Wat het beantwoordt", + "docsMenuLabel": "Pagina's van de documentatie" }, "endings": { "0": "Alles werkte.", @@ -386,5 +387,45 @@ "checksum": "Is dit bestand het bestand dat het beweert te zijn?", "checksum-check": "Is elk bestand nog wat zijn checksumbestand zegt?", "checksum-write": "Hoe weet ik later dat geen van deze bestanden is veranderd?" + }, + "docs": { + "guides": { + "guide-install": { + "title": "Installeren", + "text": "Downloaden voor Windows, macOS of Linux, het archief controleren, of installeren met Docker, npm, pip of Go." + }, + "guide-start": { + "title": "Aan de slag", + "text": "Een eerste bestand van een exacte grootte, daarna tienduizend, gecontroleerd, verwijderd en vastgelegd als recept." + }, + "guide-commands": { + "title": "Opdrachten", + "text": "Elke opdracht en elke optie met de standaardwaarde, en alle afsluitcodes." + }, + "guide-recipes": { + "title": "Recepten schrijven", + "text": "Elke sleutel van een recept, groottes, bestandsnamen, verwachte reacties, beschadigingen, archieven en presets." + }, + "recipes": { + "title": "Receptengalerij", + "text": "Kant-en-klare recepten om te downloaden voor uploads, imports, archieven, e-mail, media, CI en bulkbestanden." + }, + "guide-manifest": { + "title": "Manifest", + "text": "Elk veld van manifest.json en hoe een test het leest." + }, + "guide-formats": { + "title": "Formaatinstellingen", + "text": "Elke instelling van elk formaat, met de toegestane waarden en de standaardwaarde." + }, + "guide-frameworks": { + "title": "Testframeworks", + "text": "De bestanden in pytest, Playwright, Vitest en node:test." + }, + "guide-window": { + "title": "Desktopapp", + "text": "Het venster, scherm voor scherm." + } + } } } diff --git a/web/content/pl/docs.html b/web/content/pl/docs.html index 0ddfd969..1e99f9a9 100644 --- a/web/content/pl/docs.html +++ b/web/content/pl/docs.html @@ -1,283 +1,21 @@

    Dokumentacja

    - Wszystko, co narzędzie robi, ułożone jako pytania, z którymi ludzie naprawdę przychodzą. - README w repozytorium jest pełną dokumentacją i zawsze odpowiada - wersji, którą pobrałeś. + Jak zainstalować tfg, zrobić pierwsze pliki testowe i wszystko, co program przyjmuje i zapisuje: każda komenda i flaga, każdy klucz przepisu, każde pole manifestu i każde ustawienie każdego formatu. Te strony są po angielsku, bo powstają z samego programu przy każdym budowaniu strony, więc zawsze mówią to, co robi wersja, którą pobierasz.

    -
    -

    Jakie są komendy?

    -

    Każda robi jedną rzecz:

    - {{ template "commandList" . }} -

    - tfg tool zawiera narzędzia do plików, które już masz, na przykład sprawdzanie archiwum - przed rozpakowaniem. Narzędzia opisują każde z nich. -

    -
    - -
    -

    Jak wygenerować jeden plik o dokładnym rozmiarze?

    -

    - Podaj format, rozmiar i katalog. Rozmiary liczą się po 1024, więc 2mb to 2097152 - bajty. Zwykła liczba bajtów też zadziała, więc --size 10485761 prosi dokładnie - o tyle. -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    Przydatne flagi komendy generate:

    -
    - - - - - - - - - - - - - - - - - -
    FlagaCo robi
    --format <id>format plików, na przykład txt
    --size <rozmiar>dokładny rozmiar każdego pliku, na przykład 10mb albo liczba bajtów
    --size-range <a-b>rozmiar losowany dla każdego pliku z zakresu, na przykład 1kb-8kb. Losowanie idzie z ziarna
    --boundary <rozmiar>trzy pliki wokół limitu: bajt pod, dokładnie limit, bajt nad
    --count <n>ile plików zapisać. Domyślnie 1
    --name <szablon>szablon nazwy, na przykład invoice_{index:04}.txt
    --out <katalog>katalog, do którego trafiają pliki
    --seed <n>ziarno przebiegu. To samo ziarno daje te same bajty
    --set <k>=<v>ustawienie formatu, można powtarzać
    --damage <nazwa>celowo psuje pliki, można powtarzać, stosowane po kolei. Listę wypisuje tfg damage
    --expected <wynik>accept, reject, sanitize albo unspecified
    --dry-runpolicz i pokaż, nie zapisuj niczego
    --jsonwypisz manifest na standardowe wyjście
    -
    -
    - -
    -

    Jak zrobić plik celowo zepsuty?

    -

    - Każdy inny plik, który to narzędzie zapisuje, jest poprawny z definicji, co odpowiada na dwa - z trzech pytań walidatora uploadu. --damage odpowiada na trzecie - czy plik w ogóle - się otwiera. Plik powstaje normalnie i dopiero potem zostaje zepsuty, więc dalej ma zamówiony - rozmiar. -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - Ustawienia idą po dwukropku. Flagę można powtarzać, a kolejność zapisu jest kolejnością - stosowania. tfg damage wypisuje, co ta wersja umie i co każde uszkodzenie - przyjmuje. -

    -

    W przepisie klucz jest listą, nazw albo ustawień:

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - Uszkodzony plik dostaje w manifeście expected: reject, a obok niego zapisane - uszkodzenie. Dwie rzeczy są odmawiane, zanim cokolwiek powstanie, bo każda zostawiłaby na - dysku plik, który manifest opisuje nieprawdziwie: -

    -
      -
    • plik mniejszy niż potrzebuje uszkodzenie, bo wyszedłby nietknięty
    • -
    • - expected: accept obok uszkodzenia, bo nic nie mogłoby tego spełnić. Napisz - sanitize, jeśli system pod testem ma plik naprawić, albo - unspecified, jeśli właśnie o to pytasz -
    • -
    -

    - Trzeciej rzeczy nie da się wiedzieć z góry. Jeśli uszkodzenie przebiegnie i nie ruszy ani - jednego bajtu, taki plik zostaje odrzucony zamiast zapisany - przebieg idzie dalej, mówi, - którego pliku to dotyczyło, i kończy się kodem częściowego wyniku. -

    -

    - Krok po kroku, z testem czytającym manifest: jak zrobić uszkodzony plik do testów. -

    +
    +

    Strony dokumentacji

    + {{ template "linkCards" .Docs }}
    -
    -

    Jak wygląda przepis?

    -

    - Przepis to plik YAML opisujący cały przebieg. Commitujesz go obok testów i dane testowe przestają - być binariami w repozytorium - każdy może je odtworzyć, co do bajta, z pliku o długości kilkuset - znaków. -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - Każdy cel potrzebuje dokładnie jednego z: size, size-range, - boundary albo contains. Dwa naraz to błąd, brak też. Niepoprawny przepis - nie tworzy ani jednego pliku i zgłasza wszystkie problemy naraz, a nie pierwszy - z brzegu, przy czym każdy nazywa ustawienie, o które chodzi. -

    +
    +

    Co robi narzędzie, temat po temacie

    + {{ template "linkCards" (.PagesOf "formats" "presets" "damage" "samples" "upload-tests" "ci" "exact-size") }}
    -
    -

    Jak zadeklarować, co system ma zrobić z plikiem?

    -

    Krótka forma, gdy wystarczy sam wynik, i długa, gdy liczy się powód:

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - Wyniki to accept, reject, sanitize i - unspecified. Powody są zamkniętą listą, żeby raport mógł po nich grupować: - content_malformed, count_limit, dimensions_limit, - duplicate, encoding_invalid, extension_rule, - filename_invalid, filename_too_long, filename_traversal, - malware_signature, mime_mismatch, nesting_depth, - none, size_limit i size_zero. -

    -

    - Powód nazywa regułę, o którą chodzi, a nie werdykt. Dlatego ten sam powód może - stać pod jednym i pod drugim wynikiem - plik bajt pod limitem jest accept, a reguła, - której dotyczy, to dalej size_limit. -

    -
    - -
    -

    Co zawiera manifest?

    -

    - Powstaje obok plików na koniec każdego przebiegu, także takiego, który został przerwany. Jedna - pozycja na plik: -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "{{ .Facts.Version }}" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - Do tego dochodzi recipe_hash, gdy przebieg pochodził z przepisu, oraz - preset i overrides, gdy pochodził z presetu - żeby manifest zawsze dało - się prześledzić z powrotem do tego, co go wyprodukowało. -

    -

    - Każdy wpis niesie też target_id, czyli id celu z przepisu, który - wyprodukował ten plik, a summary.by_target liczy pliki, które dał każdy cel. Przepis - z kilkoma celami da się dzięki temu sprawdzać cel po celu, bez czytania nazw plików. -

    -
    - -
    -

    Czym jest preset?

    -

    - To gotowy zestaw plików odpowiadający na częste pytanie testowe, żebyś nie musiał projektować - zestawu samodzielnie. Presety są pod spodem zwykłymi przepisami, a eject wypisuje ten - przepis, więc możesz go od tego miejsca edytować. Każdy preset ma - własną stronę: co zwykle znajduje, co jest w zestawie i jakie ustawienia - przyjmuje. -

    - {{ template "presetsList" . }} -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show mówi, ile zestaw będzie kosztował, zanim go zbudujesz, i wprost zaznacza, kiedy - liczba jest naszą wartością zastępczą, a nie Twoim limitem. -

    -
    - -
    -

    Co znaczą kody wyjścia?

    -

    - Każde zakończenie ma własny kod, wyjście czytelne dla maszyny idzie na standardowe wyjście, - a nieudany przebieg nie pisze tam nic. Tabela jest zamrożonym kontraktem - zmiana znaczenia kodu - wymaga podniesienia wersji głównej. -

    - {{ template "exitCodesTable" . }} -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - Przebieg zatrzymany przez Ctrl+C i tak zostawia manifest i nigdy nie zostawia pliku zapisanego - w połowie, więc anulowane zadanie da się posprzątać następnym. -

    -

    - Gotowe workflow dla GitHub Actions i GitLab CI: jak generować pliki testowe w potoku CI. -

    -
    - -
    -

    Czy jest okno?

    -

    - Tak, ten sam silnik z oknem, do testowania, które nie jest skryptowane. Nie jest okrojoną wersją: - test porównuje obie powierzchnie możliwość po możliwości, a wszystko, co potrafi tylko jedna z nich, - musi być zadeklarowane i uzasadnione, zamiast po cichu się rozjeżdżać. -

    +
    +

    Nadal coś nie działa?

    - Ekrany to pojedynczy wsad, presety, kilka wsadów naraz i informacje o programie. Okno pokazuje, - ile przebieg będzie kosztował, zanim cokolwiek zapisze, melduje postęp w trakcie i da się je - przerwać w połowie bez zostawiania pliku zapisanego do połowy. Nie wczytuje jeszcze przepisu - z pliku - przepisy są na razie sprawą wiersza poleceń, a okno buduje swoje wsady w formularzu. + tfg <command> --help mówi w terminalu, co przyjmuje komenda. Każda odmowa nazywa ustawienie, którego dotyczy, mówi dlaczego i podaje wartość, która zadziała. Jeśli coś działa inaczej, niż mówi strona, zgłoś to. To błąd strony albo programu.

    diff --git a/web/content/pl/site.json b/web/content/pl/site.json index 819c4bd5..713dd74a 100644 --- a/web/content/pl/site.json +++ b/web/content/pl/site.json @@ -138,7 +138,8 @@ "colSha256": "SHA-256", "colExpected": "Oczekiwane", "colTool": "Narzędzie", - "colQuestion": "Na co odpowiada" + "colQuestion": "Na co odpowiada", + "docsMenuLabel": "Strony dokumentacji" }, "endings": { "0": "Wszystko się udało.", @@ -386,5 +387,45 @@ "checksum": "Czy ten plik jest tym, za który się podaje?", "checksum-check": "Czy każdy plik jest wciąż taki, jak podaje jego plik sum kontrolnych?", "checksum-write": "Jak później poznam, że żaden z tych plików się nie zmienił?" + }, + "docs": { + "guides": { + "guide-install": { + "title": "Instalacja", + "text": "Pobierz na Windows, macOS albo Linuksa, sprawdź archiwum albo zainstaluj przez Dockera, npm, pip lub Go." + }, + "guide-start": { + "title": "Pierwsze kroki", + "text": "Pierwszy plik o dokładnym rozmiarze, potem dziesięć tysięcy, sprawdzone, usunięte i zapisane jako przepis." + }, + "guide-commands": { + "title": "Komendy", + "text": "Każda komenda i każda flaga z wartością domyślną oraz wszystkie kody wyjścia." + }, + "guide-recipes": { + "title": "Pisanie przepisów", + "text": "Każdy klucz przepisu, rozmiary, nazwy plików, oczekiwane reakcje, uszkodzenia, archiwa i presety." + }, + "recipes": { + "title": "Galeria przepisów", + "text": "Gotowe przepisy do pobrania: uploady, importy, archiwa, e-maile, multimedia, CI i masowe pliki." + }, + "guide-manifest": { + "title": "Manifest", + "text": "Każde pole manifest.json i to, jak test je czyta." + }, + "guide-formats": { + "title": "Ustawienia formatów", + "text": "Każde ustawienie każdego formatu z dopuszczalnymi wartościami i wartością domyślną." + }, + "guide-frameworks": { + "title": "Frameworki testowe", + "text": "Pliki w testach pytest, Playwright, Vitest i node:test." + }, + "guide-window": { + "title": "Aplikacja okienkowa", + "text": "Okno programu, ekran po ekranie." + } + } } } diff --git a/web/content/pt-BR/docs.html b/web/content/pt-BR/docs.html index bb24e970..ca4753ec 100644 --- a/web/content/pt-BR/docs.html +++ b/web/content/pt-BR/docs.html @@ -1,284 +1,21 @@

    Documentação

    - Tudo o que a ferramenta faz, organizado como as perguntas com que as pessoas realmente chegam. O - README do repositório é a referência completa e sempre corresponde - à versão que você baixou. + Como instalar o tfg, criar seus primeiros arquivos de teste e tudo o que o programa aceita e escreve: cada comando e cada opção, cada chave de uma receita, cada campo do manifesto e cada configuração de cada formato. Estas páginas estão em inglês, porque são geradas pelo próprio programa a cada construção do site e por isso sempre dizem o que faz a versão que você baixa.

    -
    -

    Quais comandos existem?

    -

    Cada um faz uma única coisa:

    - {{ template "commandList" . }} -

    - tfg tool reúne as ferramentas para arquivos que você já tem, como checar um arquivo - compactado antes de descompactá-lo. Ferramentas descreve cada uma. -

    -
    - -
    -

    Como gero um único arquivo de tamanho exato?

    -

    - Informe o formato, o tamanho e o destino. Os tamanhos contam de 1024 em 1024, então 2mb - são 2097152 bytes. Uma contagem simples de bytes também funciona, então --size - 10485761 pede exatamente essa quantidade. -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    As opções úteis de generate:

    -
    - - - - - - - - - - - - - - - - - -
    OpçãoO que faz
    --format <id>formato dos arquivos, por exemplo txt
    --size <size>tamanho exato de cada arquivo, como 10mb ou uma contagem simples de bytes
    --size-range <a-b>um tamanho sorteado por arquivo dentro de um intervalo, como 1kb-8kb. O sorteio vem do seed
    --boundary <size>três arquivos ao redor de um limite: um byte abaixo, o limite, um byte acima
    --count <n>quantos arquivos produzir. Padrão 1
    --name <template>modelo de nome, por exemplo invoice_{index:04}.txt
    --out <dir>diretório onde escrever
    --seed <n>seed da execução. O mesmo seed dá os mesmos bytes
    --set <k>=<v>uma configuração de formato, repetível
    --damage <name>quebrar os arquivos de propósito, repetível e aplicado em ordem. Rode tfg damage para ver a lista
    --expected <outcome>accept, reject, sanitize ou unspecified
    --dry-runcontar e mostrar, sem escrever absolutamente nada
    --jsonescrever o manifesto na saída padrão
    -
    -
    - -
    -

    Como faço um arquivo quebrado de propósito?

    -

    - Todo outro arquivo que esta ferramenta escreve é correto por construção, o que responde a duas das - três perguntas que um validador de upload faz. --damage responde à terceira - se o - arquivo abre, afinal. O arquivo é produzido normalmente e depois quebrado, então continua com o - tamanho que você pediu. -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - As configurações vão depois de dois-pontos. A opção se repete, e a ordem em que você as escreve é a - ordem em que são aplicadas. tfg damage lista o que esta versão pode fazer e o que - cada uma aceita. -

    -

    Em uma receita a chave é uma lista, de nomes ou de configurações:

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - Um arquivo danificado recebe expected: reject no manifesto, com o dano registrado ao - lado. Duas coisas são recusadas antes de escrever qualquer coisa, porque cada uma deixaria no - disco um arquivo que o manifesto descreve errado: -

    -
      -
    • um arquivo menor do que o dano precisa, porque sairia sem alteração
    • -
    • - expected: accept ao lado de um dano, porque nada poderia cumpri-lo. Escreva - sanitize se o sistema sob teste deve reparar o arquivo, ou - unspecified se essa é a pergunta que você está fazendo -
    • -
    -

    - Uma terceira não pode ser conhecida de antemão. Se um dano roda e não move nenhum byte, esse arquivo - é descartado em vez de escrito - a execução continua, diz qual arquivo foi e termina com o - código de saída parcial. -

    -

    - Passo a passo, com um teste que lê o manifesto: como - criar um arquivo corrompido para testes. -

    +
    +

    Páginas da documentação

    + {{ template "linkCards" .Docs }}
    -
    -

    Como é uma receita?

    -

    - Uma receita é um arquivo YAML que descreve uma execução inteira. Versione-a ao lado dos seus testes - e as fixtures deixam de ser binários no seu repositório - qualquer pessoa pode reconstruí-las, - byte a byte, a partir de um arquivo de algumas centenas de caracteres. -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - Cada target precisa de exatamente uma destas chaves: size, size-range, - boundary ou contains. Duas é um erro e nenhuma também. Uma receita - inválida escreve nenhum arquivo e relata todos os problemas de uma vez em vez - de só o primeiro, cada um nomeando a configuração a que se refere. -

    +
    +

    O que a ferramenta faz, por assunto

    + {{ template "linkCards" (.PagesOf "formats" "presets" "damage" "samples" "upload-tests" "ci" "exact-size") }}
    -
    -

    Como declaro o que meu sistema deve fazer com um arquivo?

    -

    Forma curta quando o resultado basta, forma longa quando o motivo importa:

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - Os resultados são accept, reject, sanitize e - unspecified. Os motivos são uma lista fechada para que um relatório possa agrupar - por eles: content_malformed, count_limit, - dimensions_limit, duplicate, encoding_invalid, - extension_rule, filename_invalid, filename_too_long, - filename_traversal, malware_signature, mime_mismatch, - nesting_depth, none, size_limit e size_zero. -

    -

    - Um motivo nomeia a regra em jogo, não o veredito. Por isso o mesmo motivo pode - ficar sob qualquer um dos resultados - um arquivo um byte abaixo de um limite é - accept, e a regra de que se trata continua sendo size_limit. -

    -
    - -
    -

    O que há no manifesto?

    -

    - Ele é escrito ao lado dos arquivos no fim de cada execução, inclusive de uma execução interrompida. - Uma entrada por arquivo: -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "{{ .Facts.Version }}" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - Um recipe_hash é adicionado quando a execução veio de uma receita, e - preset com overrides quando veio de um preset, de modo que um - manifesto sempre pode ser rastreado até o que o produziu. -

    -

    - Cada entrada também traz target_id, o id do target da receita que produziu o arquivo, e - summary.by_target conta os arquivos a que cada target chegou. Uma receita com - vários targets pode assim ser verificada target por target sem ler nomes de arquivo. -

    -
    - -
    -

    O que é um preset?

    -

    - Um conjunto de arquivos pronto que responde a uma pergunta de teste comum, para que você não precise - desenhar o conjunto. Presets são receitas comuns por baixo, e eject imprime a - receita para você editá-la a partir dali. Cada preset tem uma página - própria com o que costuma encontrar, o que há no conjunto e cada configuração que aceita. -

    - {{ template "presetsList" . }} -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show diz quanto o conjunto custaria antes de você montá-lo, e diz abertamente quando um - número é um valor provisório nosso, e não um limite seu. -

    -
    - -
    -

    O que significam os códigos de saída?

    -

    - Cada término tem seu próprio código, a saída legível por máquina vai para a saída padrão, e uma - execução com falha não imprime nada lá. A tabela é um contrato congelado - mudar o que um código - significa exige uma versão maior. -

    - {{ template "exitCodesTable" . }} -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - Uma execução parada com Ctrl+C ainda deixa um manifesto e nunca deixa um arquivo pela metade, então - um job cancelado ainda pode ser limpo pelo seguinte. -

    -

    - Workflows prontos para GitHub Actions e GitLab CI: como - gerar arquivos de teste em um pipeline de CI. -

    -
    - -
    -

    Existe uma janela de desktop?

    -

    - Sim, o mesmo motor com uma janela por cima, para o teste que não é automatizado. Não é uma versão - reduzida: um teste compara as duas interfaces capacidade por capacidade, e tudo que só uma delas - pode fazer precisa ser declarado e justificado em vez de divergir em silêncio. -

    +
    +

    Ainda com dúvidas?

    - As telas são um lote, presets, vários lotes de uma vez e Sobre. Ela mostra quanto uma execução - custaria antes de escrever qualquer coisa, informa o progresso enquanto roda e pode ser - cancelada no meio sem deixar um arquivo pela metade. Ainda não abre um arquivo de receita - por - enquanto receitas são coisa de linha de comando, e a janela monta seus lotes no formulário. + tfg <command> --help mostra no terminal o que um comando aceita. Cada recusa nomeia a configuração a que se refere, o motivo e um valor que funcionaria. Se algo não se comportar como uma página diz, avise-nos. É um erro da página ou do programa.

    diff --git a/web/content/pt-BR/site.json b/web/content/pt-BR/site.json index 50cc0e2f..a5ca8621 100644 --- a/web/content/pt-BR/site.json +++ b/web/content/pt-BR/site.json @@ -138,7 +138,8 @@ "colSha256": "SHA-256", "colExpected": "Esperado", "colTool": "Ferramenta", - "colQuestion": "O que responde" + "colQuestion": "O que responde", + "docsMenuLabel": "Páginas da documentação" }, "endings": { "0": "Tudo funcionou.", @@ -386,5 +387,45 @@ "checksum": "Este arquivo é mesmo o que diz ser?", "checksum-check": "Cada arquivo ainda é o que diz o seu arquivo de somas de verificação?", "checksum-write": "Como vou saber depois que nenhum destes arquivos mudou?" + }, + "docs": { + "guides": { + "guide-install": { + "title": "Instalação", + "text": "Baixar para Windows, macOS ou Linux, verificar o arquivo ou instalar com Docker, npm, pip ou Go." + }, + "guide-start": { + "title": "Primeiros passos", + "text": "Um primeiro arquivo de tamanho exato, depois dez mil, verificados, removidos e escritos como receita." + }, + "guide-commands": { + "title": "Comandos", + "text": "Cada comando e cada opção com seu valor padrão, e todos os códigos de saída." + }, + "guide-recipes": { + "title": "Escrever receitas", + "text": "Cada chave de uma receita, tamanhos, nomes de arquivo, reações esperadas, danos, arquivos compactados e presets." + }, + "recipes": { + "title": "Galeria de receitas", + "text": "Receitas prontas para baixar para uploads, importações, arquivos compactados, e-mail, mídia, CI e arquivos em massa." + }, + "guide-manifest": { + "title": "Manifesto", + "text": "Cada campo do manifest.json e como um teste o lê." + }, + "guide-formats": { + "title": "Configurações dos formatos", + "text": "Cada configuração de cada formato, com os valores aceitos e o valor padrão." + }, + "guide-frameworks": { + "title": "Frameworks de teste", + "text": "Os arquivos dentro do pytest, Playwright, Vitest e node:test." + }, + "guide-window": { + "title": "Aplicativo de desktop", + "text": "A janela, tela por tela." + } + } } } diff --git a/web/content/ro/docs.html b/web/content/ro/docs.html index 121d8a55..76ea5874 100644 --- a/web/content/ro/docs.html +++ b/web/content/ro/docs.html @@ -1,286 +1,21 @@

    Documentație

    - Tot ce face instrumentul, aranjat ca întrebările cu care vin oamenii de fapt. - README-ul din repository este referința completă și se potrivește - mereu cu versiunea pe care ai descărcat-o. + Cum instalați tfg, cum faceți primele fișiere de test și tot ce primește și scrie programul: fiecare comandă și fiecare opțiune, fiecare cheie a unei rețete, fiecare câmp al manifestului și fiecare setare a fiecărui format. Aceste pagini sunt în engleză, pentru că sunt produse chiar de program la fiecare construire a site-ului și spun mereu ce face versiunea pe care o descărcați.

    -
    -

    Ce comenzi există?

    -

    Fiecare face un singur lucru:

    - {{ template "commandList" . }} -

    - tfg tool cuprinde instrumentele pentru fișiere pe care le ai deja, de exemplu verificarea - unei arhive înainte de dezarhivare. Instrumente descrie fiecare dintre - ele. -

    -
    - -
    -

    Cum generez un singur fișier de dimensiune exactă?

    -

    - Spune formatul, dimensiunea și unde merge. Dimensiunile se numără din 1024 în 1024, deci - 2mb sunt 2097152 octeți. Merge și un simplu număr de octeți, deci --size - 10485761 cere exact atât. -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    Opțiunile utile ale comenzii generate:

    -
    - - - - - - - - - - - - - - - - - -
    OpțiuneCe face
    --format <id>formatul fișierelor, de exemplu txt
    --size <size>dimensiunea exactă a fiecărui fișier, precum 10mb sau un simplu număr de octeți
    --size-range <a-b>o dimensiune extrasă pentru fiecare fișier dintr-un interval, precum 1kb-8kb. Extragerea vine din seed
    --boundary <size>trei fișiere în jurul unei limite: un octet sub, limita, un octet peste
    --count <n>câte fișiere să producă. Implicit 1
    --name <template>șablon de nume, de exemplu invoice_{index:04}.txt
    --out <dir>directorul în care se scrie
    --seed <n>seed-ul rulării. Același seed dă aceiași octeți
    --set <k>=<v>o setare de format, repetabilă
    --damage <name>strică fișierele intenționat, repetabil și aplicat în ordine. Rulează tfg damage pentru listă
    --expected <outcome>accept, reject, sanitize sau unspecified
    --dry-runnumără și arată, nu scrie absolut nimic
    --jsonscrie manifestul la ieșirea standard
    -
    -
    - -
    -

    Cum fac un fișier stricat intenționat?

    -

    - Orice alt fișier scris de acest instrument este corect prin construcție, ceea ce răspunde la două - din cele trei întrebări pe care le pune un validator de încărcare. --damage - răspunde la a treia - se deschide oare fișierul. Fișierul este produs normal și apoi stricat, - deci are în continuare dimensiunea cerută. -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - Setările se pun după două puncte. Opțiunea se repetă, iar ordinea în care le scrii este ordinea în - care se aplică. tfg damage listează ce poate face această versiune și ce acceptă - fiecare. -

    -

    Într-o rețetă cheia este o listă, de nume sau de setări:

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - Un fișier deteriorat primește expected: reject în manifest, cu deteriorarea consemnată - alături. Două lucruri sunt refuzate înainte de a se scrie ceva, pentru că fiecare ar pune pe - disc un fișier pe care manifestul îl descrie greșit: -

    -
      -
    • un fișier mai mic decât are nevoie deteriorarea, pentru că ar ieși neschimbat
    • -
    • - expected: accept alături de o deteriorare, pentru că nimic nu l-ar putea îndeplini. - Scrie sanitize dacă sistemul testat trebuie să repare fișierul sau - unspecified dacă exact asta e întrebarea pe care o pui -
    • -
    -

    - O a treia nu se poate ști dinainte. Dacă o deteriorare rulează și nu mută niciun octet, fișierul - respectiv este abandonat în loc să fie scris - rularea continuă, spune care a fost fișierul și - se termină cu codul de ieșire parțial. -

    -

    - Pas cu pas, cu un test care citește manifestul: cum faci un - fișier corupt pentru teste. -

    +
    +

    Paginile documentației

    + {{ template "linkCards" .Docs }}
    -
    -

    Cum arată o rețetă?

    -

    - O rețetă este un fișier YAML care descrie o rulare întreagă. Comite-o lângă testele tale și - fixture-urile nu mai sunt binare în repository - oricine le poate reconstrui, octet cu octet, - dintr-un fișier de câteva sute de caractere. -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - Fiecare target are nevoie de exact una dintre cheile size, size-range, - boundary sau contains. Două este o eroare și la fel niciuna. O rețetă - invalidă nu scrie niciun fișier și raportează toate problemele deodată, nu doar - prima, fiecare numind setarea la care se referă. -

    +
    +

    Ce face instrumentul, pe subiecte

    + {{ template "linkCards" (.PagesOf "formats" "presets" "damage" "samples" "upload-tests" "ci" "exact-size") }}
    -
    -

    Cum declar ce trebuie să facă sistemul meu cu un fișier?

    -

    Formă scurtă când rezultatul e de ajuns, formă lungă când contează motivul:

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - Rezultatele sunt accept, reject, sanitize și - unspecified. Motivele sunt o listă închisă ca un raport să poată grupa după ele: - content_malformed, count_limit, dimensions_limit, - duplicate, encoding_invalid, extension_rule, - filename_invalid, filename_too_long, filename_traversal, - malware_signature, mime_mismatch, nesting_depth, - none, size_limit și size_zero. -

    -

    - Un motiv numește regula în joc, nu verdictul. De aceea același motiv poate sta sub - oricare dintre rezultate - un fișier cu un octet sub o limită este accept, iar - regula la care se referă rămâne size_limit. -

    -
    - -
    -

    Ce conține manifestul?

    -

    - Se scrie lângă fișiere la sfârșitul fiecărei rulări, inclusiv a uneia întrerupte. O intrare pentru - fiecare fișier: -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "{{ .Facts.Version }}" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - Se adaugă un recipe_hash când rularea a venit dintr-o rețetă și preset cu - overrides când a venit dintr-o presetare, astfel încât un manifest poate fi mereu - urmărit până la ce l-a produs. -

    -

    - Fiecare intrare poartă și target_id, id-ul targetului din rețeta care a produs - fișierul, iar summary.by_target numără fișierele la care a ajuns fiecare target. O - rețetă cu mai multe targeturi poate fi verificată astfel target cu target, fără a citi nume de - fișiere. -

    -
    - -
    -

    Ce este o presetare?

    -

    - Un set de fișiere gata făcut care răspunde unei întrebări de test obișnuite, ca să nu trebuiască să - proiectezi tu setul. Presetările sunt rețete obișnuite pe dedesubt, iar eject - afișează rețeta ca s-o poți edita de acolo. Fiecare presetare are o - pagină proprie cu ce găsește de obicei, ce este în set și fiecare setare pe care o acceptă. -

    - {{ template "presetsList" . }} -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show îți spune cât ar costa setul înainte să-l construiești și spune pe față când un - număr este o valoare provizorie de-a noastră, nu o limită de-a ta. -

    -
    - -
    -

    Ce înseamnă codurile de ieșire?

    -

    - Fiecare final are propriul cod, ieșirea citibilă de mașină merge la ieșirea standard, iar o rulare - eșuată nu tipărește nimic acolo. Tabelul este un contract înghețat - schimbarea sensului unui - cod cere o versiune majoră. -

    - {{ template "exitCodesTable" . }} -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - O rulare oprită cu Ctrl+C lasă totuși un manifest și nu lasă niciodată un fișier scris pe jumătate, - așa că un job anulat poate fi curățat de următorul. -

    -

    - Workflow-uri gata făcute pentru GitHub Actions și GitLab CI: - cum generezi fișiere de test într-un pipeline CI. -

    -
    - -
    -

    Există o fereastră desktop?

    -

    - Da, același motor cu o fereastră deasupra, pentru testarea care nu e automatizată. Nu e o versiune - redusă: un test compară cele două interfețe capacitate cu capacitate, iar tot ce poate face doar - una dintre ele trebuie declarat și justificat, nu lăsat să divergă pe tăcute. -

    +
    +

    Tot nu merge?

    - Ecranele sunt un lot, presetări, mai multe loturi deodată și Despre. Arată cât ar costa o rulare - înainte să scrie ceva, raportează progresul cât rulează și poate fi anulată pe la jumătate fără - să lase un fișier scris pe jumătate. Nu deschide încă un fișier de rețetă - rețetele sunt - deocamdată treaba liniei de comandă, iar fereastra își construiește loturile în formular. + tfg <command> --help arată în terminal ce primește o comandă. Fiecare refuz numește setarea la care se referă, motivul și o valoare care ar funcționa. Dacă ceva nu se comportă cum spune o pagină de aici, semnalați-o. Este o greșeală a paginii sau a programului.

    diff --git a/web/content/ro/site.json b/web/content/ro/site.json index 427bc906..776f8b27 100644 --- a/web/content/ro/site.json +++ b/web/content/ro/site.json @@ -138,7 +138,8 @@ "colSha256": "SHA-256", "colExpected": "Așteptat", "colTool": "Instrument", - "colQuestion": "La ce răspunde" + "colQuestion": "La ce răspunde", + "docsMenuLabel": "Paginile documentației" }, "endings": { "0": "Totul a mers.", @@ -386,5 +387,45 @@ "checksum": "Este acest fișier cel care pretinde că este?", "checksum-check": "Corespunde fiecare fișier în continuare cu fișierul lui de sume de control?", "checksum-write": "Cum voi ști mai târziu că niciunul dintre aceste fișiere nu s-a schimbat?" + }, + "docs": { + "guides": { + "guide-install": { + "title": "Instalare", + "text": "Descărcare pentru Windows, macOS sau Linux, verificarea arhivei sau instalare cu Docker, npm, pip ori Go." + }, + "guide-start": { + "title": "Primii pași", + "text": "Un prim fișier de dimensiune exactă, apoi zece mii, verificate, șterse și scrise ca rețetă." + }, + "guide-commands": { + "title": "Comenzi", + "text": "Fiecare comandă și fiecare opțiune cu valoarea implicită, și toate codurile de ieșire." + }, + "guide-recipes": { + "title": "Scrierea rețetelor", + "text": "Fiecare cheie a unei rețete, dimensiuni, nume de fișiere, reacții așteptate, deteriorări, arhive și presetări." + }, + "recipes": { + "title": "Galeria de rețete", + "text": "Rețete gata de descărcat pentru încărcări, importuri, arhive, e-mail, media, CI și fișiere în masă." + }, + "guide-manifest": { + "title": "Manifest", + "text": "Fiecare câmp din manifest.json și cum îl citește un test." + }, + "guide-formats": { + "title": "Setările formatelor", + "text": "Fiecare setare a fiecărui format, cu valorile acceptate și valoarea implicită." + }, + "guide-frameworks": { + "title": "Framework-uri de test", + "text": "Fișierele în pytest, Playwright, Vitest și node:test." + }, + "guide-window": { + "title": "Aplicația desktop", + "text": "Fereastra, ecran cu ecran." + } + } } } diff --git a/web/content/ru/docs.html b/web/content/ru/docs.html index 5f6729de..e033a292 100644 --- a/web/content/ru/docs.html +++ b/web/content/ru/docs.html @@ -1,285 +1,21 @@

    Документация

    - Всё, что делает инструмент, разложено по вопросам, с которыми люди действительно приходят. - README в репозитории - полный справочник, и он всегда - соответствует скачанной вами сборке. + Как установить tfg, создать первые тестовые файлы, и всё, что программа принимает и записывает: каждая команда и каждый флаг, каждый ключ рецепта, каждое поле манифеста и каждая настройка каждого формата. Эти страницы на английском, потому что они создаются из самой программы при каждой сборке сайта и поэтому всегда говорят то, что делает версия, которую вы скачиваете.

    -
    -

    Какие есть команды?

    -

    Каждая делает одно дело:

    - {{ template "commandList" . }} -

    - В tfg tool собраны инструменты для уже имеющихся файлов, например проверка архива - перед распаковкой. На странице Инструменты описан каждый из них. -

    -
    - -
    -

    Как создать один файл точного размера?

    -

    - Укажите формат, размер и место назначения. Размеры считаются по 1024, поэтому 2mb - это - 2097152 байта. Подойдёт и простое число байт, так что --size 10485761 запрашивает - ровно столько. -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    Полезные флаги команды generate:

    -
    - - - - - - - - - - - - - - - - - -
    ФлагЧто делает
    --format <id>формат файлов, например txt
    --size <size>точный размер каждого файла, например 10mb или простое число байт
    --size-range <a-b>размер, выбираемый для каждого файла из диапазона, например 1kb-8kb. Выбор идёт от seed
    --boundary <size>три файла вокруг лимита: на байт меньше, сам лимит, на байт больше
    --count <n>сколько файлов создать. По умолчанию 1
    --name <template>шаблон имени, например invoice_{index:04}.txt
    --out <dir>каталог, в который записывать
    --seed <n>seed запуска. Один и тот же seed даёт те же байты
    --set <k>=<v>настройка формата, можно повторять
    --damage <name>намеренно испортить файлы, можно повторять, применяется по порядку. Список выводит tfg damage
    --expected <outcome>accept, reject, sanitize или unspecified
    --dry-runпосчитать и показать, ничего не записывая
    --jsonзаписать манифест в стандартный вывод
    -
    -
    - -
    -

    Как сделать намеренно сломанный файл?

    -

    - Любой другой файл, который записывает этот инструмент, корректен по построению, и это отвечает на - два из трёх вопросов, которые задаёт проверка загрузки. --damage отвечает на третий - - открывается ли файл вообще. Файл создаётся как обычно, а затем портится, поэтому у него - остаётся запрошенный размер. -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - Настройки указываются после двоеточия. Флаг можно повторять, и порядок записи - это порядок - применения. tfg damage перечисляет, что умеет эта сборка и что принимает каждый вид - повреждения. -

    -

    В рецепте ключ - это список имён или настроек:

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - Повреждённый файл получает в манифесте expected: reject с записанным рядом - повреждением. Две вещи отклоняются до записи чего-либо, потому что каждая оставила бы на диске - файл, неверно описанный манифестом: -

    -
      -
    • файл меньше, чем нужно повреждению, потому что он вышел бы без изменений
    • -
    • - expected: accept рядом с повреждением, потому что этому не мог бы соответствовать ни - один файл. Пишите sanitize, если тестируемая система должна починить файл, или - unspecified, если именно этот вопрос вы и задаёте -
    • -
    -

    - Третье заранее узнать нельзя. Если повреждение выполняется и не меняет ни одного байта, такой файл - отбрасывается, а не записывается - запуск продолжается, сообщает, что это был за файл, и - завершается кодом частичного завершения. -

    -

    - Шаг за шагом, с тестом, который читает манифест: как сделать - повреждённый файл для тестов. -

    +
    +

    Страницы документации

    + {{ template "linkCards" .Docs }}
    -
    -

    Как выглядит рецепт?

    -

    - Рецепт - это файл YAML, описывающий целый запуск. Закоммитьте его рядом с тестами, и фикстуры - перестанут быть бинарными файлами в вашем репозитории - любой сможет пересоздать их байт в байт - из файла в несколько сотен символов. -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - Каждой цели нужен ровно один из ключей size, size-range, - boundary или contains. Два - это ошибка, и ни одного - тоже. - Недопустимый рецепт записывает ни одного файла и сообщает обо всех проблемах - сразу, а не только о первой, называя каждый раз настройку, к которой она относится. -

    +
    +

    Что делает инструмент, по темам

    + {{ template "linkCards" (.PagesOf "formats" "presets" "damage" "samples" "upload-tests" "ci" "exact-size") }}
    -
    -

    Как объявить, что моя система должна делать с файлом?

    -

    Краткая форма, когда достаточно исхода, и длинная, когда важна причина:

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - Исходы - accept, reject, sanitize и unspecified. - Причины образуют закрытый список, чтобы отчёт мог по ним группировать: - content_malformed, count_limit, dimensions_limit, - duplicate, encoding_invalid, extension_rule, - filename_invalid, filename_too_long, filename_traversal, - malware_signature, mime_mismatch, nesting_depth, - none, size_limit и size_zero. -

    -

    - Причина называет действующее правило, а не вердикт. Поэтому одна и та же причина - может стоять под любым исходом - файл на байт меньше лимита получает accept, а - правило, о котором речь, всё равно size_limit. -

    -
    - -
    -

    Что в манифесте?

    -

    - Он записывается рядом с файлами в конце каждого запуска, в том числе прерванного. Одна запись на - файл: -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "{{ .Facts.Version }}" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - recipe_hash добавляется, если запуск был по рецепту, а preset с - overrides - если по пресету, так что манифест всегда можно отследить до того, что - его создало. -

    -

    - Каждая запись также содержит target_id - id цели рецепта, которая создала файл, а - summary.by_target считает файлы каждой цели. Рецепт с несколькими целями можно - поэтому проверить цель за целью, не читая имена файлов. -

    -
    - -
    -

    Что такое пресет?

    -

    - Готовый набор файлов, отвечающий на распространённый тестовый вопрос, чтобы вам не приходилось - проектировать набор самостоятельно. Пресеты - обычные рецепты внутри, а eject - выводит рецепт, чтобы вы могли отредактировать его. У каждого пресета есть - отдельная страница о том, что он обычно находит, что входит в набор и - какие настройки принимает. -

    - {{ template "presetsList" . }} -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show сообщает, чего стоил бы набор, прежде чем вы его соберёте, и прямо говорит, когда - число - наша временная подстановка, а не ваш лимит. -

    -
    - -
    -

    Что означают коды завершения?

    -

    - У каждого исхода свой код, машиночитаемый вывод идёт в стандартный вывод, а неудачный запуск ничего - туда не печатает. Таблица - замороженный контракт: смена значения кода требует повышения - мажорной версии. -

    - {{ template "exitCodesTable" . }} -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - Запуск, остановленный с помощью Ctrl+C, всё равно оставляет манифест и никогда не оставляет - наполовину записанный файл, поэтому отменённое задание может быть убрано следующим. -

    -

    - Готовые workflow для GitHub Actions и GitLab CI: как генерировать - тестовые файлы в конвейере CI. -

    -
    - -
    -

    Есть ли десктопное окно?

    -

    - Да, тот же движок с окном сверху, для тестирования, которое не автоматизируется. Это не урезанная - версия: тест сравнивает два интерфейса возможность за возможностью, и всё, что умеет только один - из них, должно быть объявлено и обосновано, а не тихо расходиться. -

    +
    +

    Всё ещё не получается?

    - Экраны: одна партия, пресеты, несколько партий одновременно и о программе. Окно показывает, чего - стоил бы запуск, прежде чем что-либо записать, отображает ход работы и может быть отменено на - полпути без наполовину записанного файла. Файл рецепта оно пока не открывает - рецепты пока дело - командной строки, а окно собирает свои партии в форме. + tfg <command> --help показывает в терминале, что принимает команда. Каждый отказ называет настройку, о которой идёт речь, причину и значение, которое подойдёт. Если что-то работает не так, как сказано на странице, сообщите об этом. Это ошибка страницы или программы.

    diff --git a/web/content/ru/site.json b/web/content/ru/site.json index ab41a46b..59ea2b44 100644 --- a/web/content/ru/site.json +++ b/web/content/ru/site.json @@ -138,7 +138,8 @@ "colSha256": "SHA-256", "colExpected": "Ожидается", "colTool": "Инструмент", - "colQuestion": "На что отвечает" + "colQuestion": "На что отвечает", + "docsMenuLabel": "Страницы документации" }, "endings": { "0": "Всё сработало.", @@ -386,5 +387,45 @@ "checksum": "Тот ли это файл, за который он себя выдаёт?", "checksum-check": "Соответствует ли каждый файл тому, что записано в его файле контрольных сумм?", "checksum-write": "Как я потом узнаю, что ни один из этих файлов не изменился?" + }, + "docs": { + "guides": { + "guide-install": { + "title": "Установка", + "text": "Скачать для Windows, macOS или Linux, проверить архив или установить через Docker, npm, pip или Go." + }, + "guide-start": { + "title": "Первые шаги", + "text": "Первый файл точного размера, затем десять тысяч, проверенные, удалённые и записанные как рецепт." + }, + "guide-commands": { + "title": "Команды", + "text": "Каждая команда и каждый флаг со значением по умолчанию, и все коды завершения." + }, + "guide-recipes": { + "title": "Как писать рецепты", + "text": "Каждый ключ рецепта, размеры, имена файлов, ожидаемые реакции, повреждения, архивы и пресеты." + }, + "recipes": { + "title": "Галерея рецептов", + "text": "Готовые рецепты для загрузки: выгрузки, импорт, архивы, почта, медиа, CI и массовые файлы." + }, + "guide-manifest": { + "title": "Манифест", + "text": "Каждое поле manifest.json и то, как его читает тест." + }, + "guide-formats": { + "title": "Настройки форматов", + "text": "Каждая настройка каждого формата с допустимыми значениями и значением по умолчанию." + }, + "guide-frameworks": { + "title": "Тестовые фреймворки", + "text": "Файлы внутри pytest, Playwright, Vitest и node:test." + }, + "guide-window": { + "title": "Настольное приложение", + "text": "Окно программы, экран за экраном." + } + } } } diff --git a/web/content/th/docs.html b/web/content/th/docs.html index 93caebac..81315edb 100644 --- a/web/content/th/docs.html +++ b/web/content/th/docs.html @@ -1,276 +1,21 @@

    เอกสาร

    - ทุกอย่างที่เครื่องมือทำได้ จัดเรียงตามคำถามที่ผู้คนมาถามจริงๆ README - ในรีโพซิทอรีเป็นข้อมูลอ้างอิงฉบับสมบูรณ์และตรงกับบิลด์ที่คุณดาวน์โหลดเสมอ + วิธีติดตั้ง tfg สร้างไฟล์ทดสอบชุดแรก และทุกอย่างที่โปรแกรมรับและเขียน ได้แก่ ทุกคำสั่งและทุกแฟล็ก ทุกคีย์ของสูตร ทุกฟิลด์ของแมนิเฟสต์ และทุกการตั้งค่าของทุกรูปแบบไฟล์ หน้าเหล่านี้เป็นภาษาอังกฤษ เพราะสร้างจากตัวโปรแกรมเองทุกครั้งที่สร้างเว็บไซต์ จึงตรงกับสิ่งที่เวอร์ชันที่คุณดาวน์โหลดทำเสมอ

    -
    -

    มีคำสั่งอะไรบ้าง

    -

    แต่ละคำสั่งทำสิ่งเดียว:

    - {{ template "commandList" . }} -

    - tfg tool รวมเครื่องมือสำหรับไฟล์ที่คุณมีอยู่แล้ว เช่น การตรวจไฟล์บีบอัดก่อนแตกไฟล์ - เครื่องมือ อธิบายเครื่องมือแต่ละตัว -

    -
    - -
    -

    สร้างไฟล์เดียวที่ขนาดแม่นยำได้อย่างไร

    -

    - ระบุรูปแบบ ขนาด และปลายทาง ขนาดนับเป็นทีละ 1024 ดังนั้น 2mb คือ 2097152 ไบต์ - ใช้จำนวนไบต์ธรรมดาก็ได้ ดังนั้น --size 10485761 ขอจำนวนนั้นพอดี -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    แฟลกที่มีประโยชน์ของ generate:

    -
    - - - - - - - - - - - - - - - - - -
    แฟลกทำอะไร
    --format <id>รูปแบบของไฟล์ เช่น txt
    --size <size>ขนาดที่แม่นยำของแต่ละไฟล์ เช่น 10mb หรือจำนวนไบต์ธรรมดา
    --size-range <a-b>ขนาดที่สุ่มต่อไฟล์จากช่วง เช่น 1kb-8kb การสุ่มมาจากซีด
    --boundary <size>สามไฟล์รอบขีดจำกัด: น้อยกว่าหนึ่งไบต์ เท่ากับขีดจำกัด และมากกว่าหนึ่งไบต์
    --count <n>จะสร้างกี่ไฟล์ ค่าเริ่มต้น 1
    --name <template>แม่แบบชื่อ เช่น invoice_{index:04}.txt
    --out <dir>ไดเรกทอรีที่จะเขียนลงไป
    --seed <n>ซีดของการรัน ซีดเดียวกันให้ไบต์เดียวกัน
    --set <k>=<v>การตั้งค่ารูปแบบ ระบุซ้ำได้
    --damage <name>ทำให้ไฟล์เสียหายโดยตั้งใจ ระบุซ้ำได้และใช้ตามลำดับ รัน tfg damage เพื่อดูรายการ
    --expected <outcome>accept, reject, sanitize หรือ unspecified
    --dry-runนับและแสดง ไม่เขียนอะไรเลย
    --jsonเขียนแมนิเฟสต์ไปยังเอาต์พุตมาตรฐาน
    -
    -
    - -
    -

    ทำไฟล์ที่เสียโดยตั้งใจได้อย่างไร

    -

    - ไฟล์อื่นทุกไฟล์ที่เครื่องมือนี้เขียนถูกต้องโดยโครงสร้าง - ซึ่งตอบสองในสามคำถามที่ตัวตรวจสอบการอัปโหลดถาม --damage ตอบข้อที่สาม - - ไฟล์เปิดได้หรือไม่ ไฟล์ถูกสร้างตามปกติแล้วจึงถูกทำให้เสีย จึงยังคงมีขนาดที่คุณขอ -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - การตั้งค่าอยู่หลังเครื่องหมายทวิภาค แฟลกระบุซ้ำได้ และลำดับที่คุณเขียนคือลำดับที่ใช้ tfg - damage แสดงว่าบิลด์นี้ทำอะไรได้บ้างและแต่ละแบบรับอะไร -

    -

    ในสูตร คีย์เป็นรายการ ของชื่อหรือของการตั้งค่า:

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - ไฟล์ที่เสียหายได้ expected: reject ในแมนิเฟสต์ พร้อมบันทึกความเสียหายไว้ข้างๆ - สองอย่างถูกปฏิเสธก่อนจะเขียนอะไร เพราะแต่ละอย่างจะวางไฟล์ที่แมนิเฟสต์อธิบายผิดไว้บนดิสก์: -

    -
      -
    • ไฟล์ที่เล็กกว่าที่ความเสียหายต้องการ เพราะจะออกมาโดยไม่เปลี่ยนแปลง
    • -
    • - expected: accept ข้างความเสียหาย เพราะไม่มีสิ่งใดทำให้เป็นจริงได้ เขียน - sanitize ถ้าระบบที่ทดสอบควรซ่อมไฟล์ หรือ unspecified - ถ้านั่นคือคำถามที่คุณกำลังถาม -
    • -
    -

    - ข้อที่สามรู้ล่วงหน้าไม่ได้ ถ้าความเสียหายทำงานแล้วไม่ขยับไบต์ใดเลย ไฟล์นั้นจะถูกทิ้งแทนที่จะถูกเขียน - - การรันดำเนินต่อ บอกว่าเป็นไฟล์ไหน และจบด้วยรหัสออกแบบบางส่วน -

    -

    - ทีละขั้น พร้อมการทดสอบที่อ่านแมนิเฟสต์: - วิธีทำไฟล์เสียหายสำหรับการทดสอบ -

    +
    +

    หน้าเอกสาร

    + {{ template "linkCards" .Docs }}
    -
    -

    สูตรหน้าตาเป็นอย่างไร

    -

    - สูตรคือไฟล์ YAML ที่อธิบายการรันทั้งหมด คอมมิตไว้ข้างการทดสอบของคุณ - แล้วฟิกซ์เจอร์จะไม่เป็นไบนารีในรีโพซิทอรีอีกต่อไป - ใครก็สร้างใหม่ได้ ไบต์ต่อไบต์ - จากไฟล์ที่ยาวไม่กี่ร้อยอักขระ -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - แต่ละ target ต้องมี size, size-range, boundary หรือ - contains อย่างใดอย่างหนึ่งพอดี มีสองอย่างคือข้อผิดพลาด ไม่มีเลยก็เป็นข้อผิดพลาด - สูตรที่ไม่ถูกต้องไม่เขียนไฟล์ใดเลย - และรายงานปัญหาทั้งหมดพร้อมกันแทนที่จะรายงานแค่ข้อแรก โดยแต่ละข้อระบุการตั้งค่าที่เกี่ยวข้อง -

    +
    +

    เครื่องมือนี้ทำอะไรได้ แยกตามหัวข้อ

    + {{ template "linkCards" (.PagesOf "formats" "presets" "damage" "samples" "upload-tests" "ci" "exact-size") }}
    -
    -

    ประกาศอย่างไรว่าระบบของฉันควรทำอะไรกับไฟล์

    -

    ใช้รูปแบบสั้นเมื่อผลลัพธ์เพียงพอ ใช้รูปแบบยาวเมื่อเหตุผลสำคัญ:

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - ผลลัพธ์คือ accept, reject, sanitize และ - unspecified เหตุผลเป็นรายการปิดเพื่อให้รายงานจัดกลุ่มตามได้: - content_malformed, count_limit, dimensions_limit, - duplicate, encoding_invalid, extension_rule, - filename_invalid, filename_too_long, filename_traversal, - malware_signature, mime_mismatch, nesting_depth, - none, size_limit และ size_zero -

    -

    - เหตุผลระบุกฎที่เกี่ยวข้อง ไม่ใช่คำตัดสิน - ด้วยเหตุนี้เหตุผลเดียวกันจึงอยู่ใต้ผลลัพธ์ใดก็ได้ - ไฟล์ที่น้อยกว่าขีดจำกัดหนึ่งไบต์คือ - accept และกฎที่เกี่ยวข้องก็ยังเป็น size_limit -

    -
    - -
    -

    แมนิเฟสต์มีอะไรบ้าง

    -

    - ถูกเขียนไว้ข้างไฟล์เมื่อจบทุกการรัน รวมถึงการรันที่ถูกขัดจังหวะ หนึ่งรายการต่อไฟล์: -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "{{ .Facts.Version }}" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - recipe_hash จะถูกเพิ่มเมื่อการรันมาจากสูตร และ preset พร้อม - overrides เมื่อมาจากพรีเซ็ต แมนิเฟสต์จึงสืบย้อนไปถึงสิ่งที่สร้างมันได้เสมอ -

    -

    - ทุกรายการยังมี target_id ซึ่งเป็นรหัสของ target ในสูตรที่สร้างไฟล์ และ - summary.by_target นับจำนวนไฟล์ที่แต่ละ target สร้างได้ สูตรที่มีหลาย target - จึงตรวจทีละ target ได้โดยไม่ต้องอ่านชื่อไฟล์ -

    -
    - -
    -

    พรีเซ็ตคืออะไร

    -

    - ชุดไฟล์สำเร็จรูปที่ตอบคำถามการทดสอบที่พบบ่อย คุณจึงไม่ต้องออกแบบชุดเอง - พรีเซ็ตเป็นสูตรธรรมดาอยู่ข้างใน และ eject - พิมพ์สูตรออกมาเพื่อให้คุณแก้ไขต่อจากตรงนั้น - แต่ละพรีเซ็ตมีหน้าของตัวเองที่บอกว่าโดยทั่วไปมันพบอะไร ในชุดมีอะไร - และรับการตั้งค่าใดบ้าง -

    - {{ template "presetsList" . }} -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show บอกว่าชุดจะมีต้นทุนเท่าไรก่อนที่คุณจะสร้าง และบอกตรงๆ - เมื่อตัวเลขใดเป็นค่าชั่วคราวของเรา ไม่ใช่ขีดจำกัดของคุณ -

    -
    - -
    -

    รหัสออกมีความหมายอย่างไร

    -

    - ทุกการจบมีรหัสของตัวเอง เอาต์พุตที่เครื่องอ่านได้ไปที่เอาต์พุตมาตรฐาน - และการรันที่ล้มเหลวไม่พิมพ์อะไรที่นั่น ตารางนี้เป็นสัญญาที่ตรึงไว้ - - การเปลี่ยนความหมายของรหัสต้องเลื่อนเวอร์ชันหลัก -

    - {{ template "exitCodesTable" . }} -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - การรันที่หยุดด้วย Ctrl+C ยังทิ้งแมนิเฟสต์ไว้ และไม่เคยทิ้งไฟล์ที่เขียนค้างครึ่งหนึ่ง - งานที่ถูกยกเลิกจึงยังถูกทำความสะอาดโดยงานถัดไปได้ -

    -

    - เวิร์กโฟลว์สำเร็จรูปสำหรับ GitHub Actions และ GitLab CI: - วิธีสร้างไฟล์ทดสอบในไปป์ไลน์ CI -

    -
    - -
    -

    มีหน้าต่างเดสก์ท็อปไหม

    -

    - มี เป็นเอนจินเดียวกันที่มีหน้าต่างครอบอยู่ สำหรับการทดสอบที่ไม่ได้เขียนสคริปต์ ไม่ใช่ฉบับตัดทอน: - มีการทดสอบเปรียบเทียบสองอินเทอร์เฟซทีละความสามารถ - และสิ่งที่ทำได้เพียงฝั่งเดียวต้องถูกประกาศและให้เหตุผล แทนที่จะแยกจากกันไปอย่างเงียบๆ -

    +
    +

    ยังติดอยู่ใช่ไหม

    - หน้าจอมีชุดเดียว พรีเซ็ต หลายชุดพร้อมกัน และเกี่ยวกับ แสดงต้นทุนของการรันก่อนเขียนอะไร - รายงานความคืบหน้าขณะรัน และยกเลิกกลางคันได้โดยไม่ทิ้งไฟล์ที่เขียนค้างครึ่งหนึ่ง - ยังเปิดไฟล์สูตรไม่ได้ - ตอนนี้สูตรเป็นเรื่องของบรรทัดคำสั่ง และหน้าต่างสร้างชุดในฟอร์ม + tfg <command> --help จะแสดงในเทอร์มินัลว่าคำสั่งหนึ่งรับอะไรบ้าง ทุกครั้งที่ปฏิเสธจะบอกการตั้งค่าที่เกี่ยวข้อง เหตุผล และค่าที่ใช้ได้ หากบางอย่างไม่ทำงานตามที่หน้านี้บอก โปรดแจ้งเรา นั่นคือข้อผิดพลาดของหน้าหรือของโปรแกรม

    diff --git a/web/content/th/site.json b/web/content/th/site.json index f6c85998..6741cf8b 100644 --- a/web/content/th/site.json +++ b/web/content/th/site.json @@ -138,7 +138,8 @@ "colSha256": "SHA-256", "colExpected": "ผลที่คาดหวัง", "colTool": "เครื่องมือ", - "colQuestion": "คำถามที่ตอบ" + "colQuestion": "คำถามที่ตอบ", + "docsMenuLabel": "หน้าเอกสาร" }, "endings": { "0": "ทุกอย่างทำงานได้", @@ -386,5 +387,45 @@ "checksum": "ไฟล์นี้ใช่ไฟล์ที่มันอ้างว่าเป็นหรือไม่", "checksum-check": "ทุกไฟล์ยังตรงกับที่ไฟล์เช็กซัมบอกไว้หรือไม่", "checksum-write": "ภายหลังจะรู้ได้อย่างไรว่าไม่มีไฟล์ใดในไฟล์เหล่านี้เปลี่ยนไป" + }, + "docs": { + "guides": { + "guide-install": { + "title": "การติดตั้ง", + "text": "ดาวน์โหลดสำหรับ Windows, macOS หรือ Linux ตรวจสอบไฟล์บีบอัด หรือติดตั้งด้วย Docker, npm, pip หรือ Go" + }, + "guide-start": { + "title": "เริ่มต้นใช้งาน", + "text": "ไฟล์แรกขนาดพอดี แล้วหนึ่งหมื่นไฟล์ ตรวจสอบ ลบ และเขียนเป็นสูตร" + }, + "guide-commands": { + "title": "คำสั่ง", + "text": "ทุกคำสั่งและทุกแฟล็กพร้อมค่าเริ่มต้น และรหัสออกทั้งหมด" + }, + "guide-recipes": { + "title": "การเขียนสูตร", + "text": "ทุกคีย์ของสูตร ขนาด ชื่อไฟล์ ปฏิกิริยาที่คาดหวัง ความเสียหาย ไฟล์บีบอัด และพรีเซ็ต" + }, + "recipes": { + "title": "คลังสูตร", + "text": "สูตรพร้อมดาวน์โหลดสำหรับการอัปโหลด การนำเข้า ไฟล์บีบอัด อีเมล สื่อ CI และไฟล์จำนวนมาก" + }, + "guide-manifest": { + "title": "แมนิเฟสต์", + "text": "ทุกฟิลด์ของ manifest.json และวิธีที่การทดสอบอ่าน" + }, + "guide-formats": { + "title": "การตั้งค่ารูปแบบไฟล์", + "text": "ทุกการตั้งค่าของทุกรูปแบบไฟล์ พร้อมค่าที่รับได้และค่าเริ่มต้น" + }, + "guide-frameworks": { + "title": "เฟรมเวิร์กการทดสอบ", + "text": "ไฟล์ภายใน pytest, Playwright, Vitest และ node:test" + }, + "guide-window": { + "title": "แอปเดสก์ท็อป", + "text": "หน้าต่างโปรแกรม ทีละหน้าจอ" + } + } } } diff --git a/web/content/tr/docs.html b/web/content/tr/docs.html index 94983a57..2b179fe7 100644 --- a/web/content/tr/docs.html +++ b/web/content/tr/docs.html @@ -1,282 +1,21 @@

    Dokümantasyon

    - Aracın yaptığı her şey, insanların gerçekten geldiği sorular şeklinde düzenlendi. - Depodaki README tam başvurudur ve her zaman indirdiğiniz sürümle - eşleşir. + tfg nasıl kurulur, ilk test dosyalarınız nasıl yapılır ve programın aldığı ve yazdığı her şey: her komut ve her seçenek, bir tarifin her anahtarı, manifestin her alanı ve her biçimin her ayarı. Bu sayfalar İngilizcedir, çünkü site her oluşturulduğunda programın kendisinden üretilirler ve bu yüzden her zaman indirdiğiniz sürümün ne yaptığını söylerler.

    -
    -

    Hangi komutlar var?

    -

    Her biri tek bir iş yapar:

    - {{ template "commandList" . }} -

    - tfg tool, elinizdeki dosyalar için araçları içerir, örneğin bir arşivi açmadan önce - denetlemek. Araçlar sayfası her birini anlatır. -

    -
    - -
    -

    Tam boyutta tek bir dosyayı nasıl üretirim?

    -

    - Biçimi, boyutu ve nereye gideceğini söyleyin. Boyutlar 1024'lerle sayılır, yani 2mb - 2097152 bayttır. Düz bir bayt sayısı da olur, yani --size 10485761 tam o kadarını - ister. -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    generate için işe yarar bayraklar:

    -
    - - - - - - - - - - - - - - - - - -
    BayrakNe yapar
    --format <id>dosyaların biçimi, örneğin txt
    --size <size>her dosyanın tam boyutu, 10mb gibi veya düz bir bayt sayısı
    --size-range <a-b>bir aralıktan dosya başına çekilen boyut, 1kb-8kb gibi. Çekiliş seed'den gelir
    --boundary <size>bir sınırın çevresinde üç dosya: bir bayt altı, sınırın kendisi, bir bayt üstü
    --count <n>kaç dosya üretileceği. Varsayılan 1
    --name <template>ad şablonu, örneğin invoice_{index:04}.txt
    --out <dir>yazılacak dizin
    --seed <n>çalıştırmanın seed'i. Aynı seed aynı baytları verir
    --set <k>=<v>bir biçim ayarı, tekrarlanabilir
    --damage <name>dosyaları kasıtlı bozar, tekrarlanabilir ve sırayla uygulanır. Liste için tfg damage çalıştırın
    --expected <outcome>accept, reject, sanitize veya unspecified
    --dry-runsay ve göster, hiçbir şey yazma
    --jsonmanifesti standart çıktıya yaz
    -
    -
    - -
    -

    Kasıtlı bozuk bir dosyayı nasıl yaparım?

    -

    - Bu aracın yazdığı diğer her dosya yapısı gereği doğrudur ve bu, bir yükleme doğrulayıcısının sorduğu - üç sorudan ikisini yanıtlar. --damage üçüncüsünü yanıtlar - dosya hiç açılıyor mu. - Dosya normal üretilir, sonra bozulur, böylece hâlâ istediğiniz boyuttadır. -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - Ayarlar iki noktadan sonra gelir. Bayrak tekrarlanır ve yazdığınız sıra uygulanma sırasıdır. - tfg damage bu sürümün neler yapabildiğini ve her birinin ne aldığını listeler. -

    -

    Bir tarifte anahtar, adlardan veya ayarlardan oluşan bir listedir:

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - Hasarlı bir dosya manifestte expected: reject alır, hasar yanında kaydedilir. İki şey - bir şey yazılmadan önce reddedilir, çünkü her biri aksi hâlde diske manifestin yanlış tarif - ettiği bir dosya koyardı: -

    -
      -
    • hasarın gerektirdiğinden küçük bir dosya, çünkü değişmeden çıkardı
    • -
    • - bir hasarın yanında expected: accept, çünkü hiçbir şey bunu karşılayamaz. Test edilen - sistemin dosyayı onarması amaçlanıyorsa sanitize, sorduğunuz soru buysa - unspecified yazın -
    • -
    -

    - Üçüncüsü önceden bilinemez. Bir hasar çalışıp hiçbir baytı oynatmazsa o dosya yazılmak yerine atılır - - çalıştırma sürer, hangi dosya olduğunu söyler ve kısmi çıkış koduyla biter. -

    -

    - Adım adım, bildirimi okuyan bir testle: test için bozuk dosya - nasıl yapılır. -

    +
    +

    Dokümantasyon sayfaları

    + {{ template "linkCards" .Docs }}
    -
    -

    Bir tarif nasıl görünür?

    -

    - Tarif, tüm bir çalıştırmayı anlatan bir YAML dosyasıdır. Testlerinizin yanına commit edin, - fixture'lar deponuzda ikili dosya olmaktan çıkar - herkes onları birkaç yüz karakterlik bir - dosyadan bayt bayt yeniden kurabilir. -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - Her target, size, size-range, boundary veya - contains anahtarlarından tam birine ihtiyaç duyar. İkisi hatadır, hiçbiri de öyle. - Geçersiz bir tarif hiç dosya yazmaz ve yalnızca ilkini değil tüm sorunları bir - seferde bildirir, her biri ilgili ayarı adlandırır. -

    +
    +

    Araç ne yapar, konu konu

    + {{ template "linkCards" (.PagesOf "formats" "presets" "damage" "samples" "upload-tests" "ci" "exact-size") }}
    -
    -

    Sistemimin bir dosyayla ne yapması gerektiğini nasıl bildiririm?

    -

    Sonuç yeterliyse kısa biçim, neden önemliyse uzun biçim:

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - Sonuçlar accept, reject, sanitize ve - unspecified. Nedenler, bir rapor onlara göre gruplayabilsin diye kapalı bir - listedir: content_malformed, count_limit, - dimensions_limit, duplicate, encoding_invalid, - extension_rule, filename_invalid, filename_too_long, - filename_traversal, malware_signature, mime_mismatch, - nesting_depth, none, size_limit ve - size_zero. -

    -

    - Bir neden söz konusu kuralı adlandırır, hükmü değil. Bu yüzden aynı neden iki - sonucun altında da durabilir - sınırın bir bayt altındaki dosya accept olur ve söz - konusu kural yine size_limit kalır. -

    -
    - -
    -

    Manifestte ne var?

    -

    - Her çalıştırmanın sonunda, kesilen çalıştırma dahil, dosyaların yanına yazılır. Dosya başına bir - girdi: -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "{{ .Facts.Version }}" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - Çalıştırma bir tariften geldiyse bir recipe_hash, bir hazır ayardan geldiyse - overrides ile birlikte preset eklenir, böylece bir manifest her zaman - onu üreten şeye kadar izlenebilir. -

    -

    - Her girdi ayrıca dosyayı üreten tarifteki hedefin kimliği olan target_id taşır ve - summary.by_target her hedefin kaç dosyaya vardığını sayar. Birkaç hedefli bir tarif - böylece dosya adlarını okumadan hedef hedef denetlenebilir. -

    -
    - -
    -

    Hazır ayar nedir?

    -

    - Yaygın bir test sorusunu yanıtlayan hazır bir dosya seti, böylece seti kendiniz tasarlamanız - gerekmez. Hazır ayarlar altta sıradan tariflerdir ve eject tarifi yazdırır, oradan - düzenleyebilirsiniz. Her hazır ayarın genelde ne bulduğunu, sette ne olduğunu ve kabul ettiği - her ayarı anlatan kendi sayfası vardır. -

    - {{ template "presetsList" . }} -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show, seti kurmadan önce neye mal olacağını söyler ve bir sayının sizin sınırınız değil - bizim geçici değerimiz olduğunu açıkça belirtir. -

    -
    - -
    -

    Çıkış kodları ne anlama gelir?

    -

    - Her sonun kendi kodu vardır, makine tarafından okunabilir çıktı standart çıktıya gider ve başarısız - bir çalıştırma orada hiçbir şey yazdırmaz. Tablo dondurulmuş bir sözleşmedir - bir kodun - anlamını değiştirmek büyük sürüm artışı gerektirir. -

    - {{ template "exitCodesTable" . }} -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - Ctrl+C ile durdurulan bir çalıştırma yine bir manifest bırakır ve asla yarım yazılmış bir dosya - bırakmaz, böylece iptal edilen bir işi bir sonraki temizleyebilir. -

    -

    - GitHub Actions ve GitLab CI için hazır iş akışları: CI - hattında test dosyaları nasıl üretilir. -

    -
    - -
    -

    Masaüstü penceresi var mı?

    -

    - Evet, betiklenmeyen test için üzerine bir pencere konmuş aynı motor. Kırpılmış bir sürüm değildir: - bir test iki arayüzü yetenek yetenek karşılaştırır ve yalnızca birinin yapabildiği her şey - sessizce ayrışmak yerine bildirilip gerekçelendirilmelidir. -

    +
    +

    Hâlâ takıldınız mı?

    - Ekranlar tek bir grup, hazır ayarlar, aynı anda birkaç grup ve hakkında. Bir çalıştırmanın neye mal - olacağını bir şey yazmadan önce gösterir, çalışırken ilerlemeyi bildirir ve yarım yazılmış dosya - bırakmadan yarıda iptal edilebilir. Henüz bir tarif dosyası açmaz - tarifler şimdilik komut - satırının işidir ve pencere gruplarını formda kurar. + tfg <command> --help bir komutun ne aldığını terminalde gösterir. Her ret, ilgili ayarı, nedenini ve işe yarayacak bir değeri söyler. Bir şey buradaki bir sayfanın dediği gibi davranmıyorsa bildirin. Bu, sayfanın ya da programın bir hatasıdır.

    diff --git a/web/content/tr/site.json b/web/content/tr/site.json index 69a3aac4..f0c42af2 100644 --- a/web/content/tr/site.json +++ b/web/content/tr/site.json @@ -138,7 +138,8 @@ "colSha256": "SHA-256", "colExpected": "Beklenen", "colTool": "Araç", - "colQuestion": "Neyi yanıtlar" + "colQuestion": "Neyi yanıtlar", + "docsMenuLabel": "Dokümantasyon sayfaları" }, "endings": { "0": "Her şey çalıştı.", @@ -386,5 +387,45 @@ "checksum": "Bu dosya, olduğunu söylediği dosya mı?", "checksum-check": "Her dosya hâlâ sağlama toplamı dosyasının söylediği gibi mi?", "checksum-write": "Bu dosyaların hiçbirinin değişmediğini sonradan nasıl anlarım?" + }, + "docs": { + "guides": { + "guide-install": { + "title": "Kurulum", + "text": "Windows, macOS veya Linux için indirin, arşivi doğrulayın ya da Docker, npm, pip veya Go ile kurun." + }, + "guide-start": { + "title": "Başlarken", + "text": "Tam boyutta ilk dosya, sonra on bin dosya, doğrulanmış, silinmiş ve tarif olarak yazılmış." + }, + "guide-commands": { + "title": "Komutlar", + "text": "Her komut ve her seçenek varsayılan değeriyle, ve tüm çıkış kodları." + }, + "guide-recipes": { + "title": "Tarif yazmak", + "text": "Bir tarifin her anahtarı, boyutlar, dosya adları, beklenen tepkiler, bozmalar, arşivler ve hazır ayarlar." + }, + "recipes": { + "title": "Tarif galerisi", + "text": "Yüklemeler, içe aktarmalar, arşivler, e-posta, medya, CI ve toplu dosyalar için indirilmeye hazır tarifler." + }, + "guide-manifest": { + "title": "Manifest", + "text": "manifest.json dosyasının her alanı ve bir testin onu nasıl okuduğu." + }, + "guide-formats": { + "title": "Biçim ayarları", + "text": "Her biçimin her ayarı, kabul ettiği değerler ve varsayılan değeriyle." + }, + "guide-frameworks": { + "title": "Test çatıları", + "text": "pytest, Playwright, Vitest ve node:test içindeki dosyalar." + }, + "guide-window": { + "title": "Masaüstü uygulaması", + "text": "Pencere, ekran ekran." + } + } } } diff --git a/web/content/uk/docs.html b/web/content/uk/docs.html index ef2dd079..fe7a70ff 100644 --- a/web/content/uk/docs.html +++ b/web/content/uk/docs.html @@ -1,284 +1,21 @@

    Документація

    - Усе, що робить інструмент, розкладено за питаннями, з якими люди справді приходять. - README у репозиторії - повний довідник, і він завжди відповідає - завантаженій вами збірці. + Як встановити tfg, створити перші тестові файли, і все, що програма приймає та записує: кожна команда й кожен прапорець, кожен ключ рецепта, кожне поле маніфесту та кожне налаштування кожного формату. Ці сторінки англійською, бо вони створюються із самої програми під час кожного збирання сайту і тому завжди кажуть те, що робить версія, яку ви завантажуєте.

    -
    -

    Які є команди?

    -

    Кожна робить одну справу:

    - {{ template "commandList" . }} -

    - У tfg tool зібрано інструменти для наявних файлів, наприклад перевірку архіву перед - розпакуванням. На сторінці Інструменти описано кожен із них. -

    -
    - -
    -

    Як створити один файл точного розміру?

    -

    - Укажіть формат, розмір і місце призначення. Розміри рахуються по 1024, тому 2mb - це - 2097152 байти. Підійде й просте число байтів, тож --size 10485761 запитує рівно - стільки. -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    Корисні прапорці команди generate:

    -
    - - - - - - - - - - - - - - - - - -
    ПрапорецьЩо робить
    --format <id>формат файлів, наприклад txt
    --size <size>точний розмір кожного файлу, наприклад 10mb або просте число байтів
    --size-range <a-b>розмір, що вибирається для кожного файлу з діапазону, наприклад 1kb-8kb. Вибір іде від seed
    --boundary <size>три файли навколо ліміту: на байт менше, сам ліміт, на байт більше
    --count <n>скільки файлів створити. За замовчуванням 1
    --name <template>шаблон імені, наприклад invoice_{index:04}.txt
    --out <dir>каталог, у який записувати
    --seed <n>seed запуску. Той самий seed дає ті самі байти
    --set <k>=<v>налаштування формату, можна повторювати
    --damage <name>навмисно зіпсувати файли, можна повторювати, застосовується по порядку. Список виводить tfg damage
    --expected <outcome>accept, reject, sanitize або unspecified
    --dry-runпорахувати й показати, нічого не записуючи
    --jsonзаписати маніфест у стандартний вивід
    -
    -
    - -
    -

    Як зробити навмисно зламаний файл?

    -

    - Будь-який інший файл, що його записує цей інструмент, коректний за побудовою, і це відповідає на два - з трьох питань, які ставить перевірка завантаження. --damage відповідає на третє - - чи відкривається файл узагалі. Файл створюється як зазвичай, а потім псується, тому в нього - лишається запитаний розмір. -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - Налаштування вказуються після двокрапки. Прапорець можна повторювати, і порядок запису - це порядок - застосування. tfg damage перелічує, що вміє ця збірка та що приймає кожен вид - пошкодження. -

    -

    У рецепті ключ - це список імен або налаштувань:

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - Пошкоджений файл отримує в маніфесті expected: reject із записаним поруч пошкодженням. - Дві речі відхиляються до запису чого-небудь, бо кожна залишила б на диску файл, неправильно - описаний маніфестом: -

    -
      -
    • файл менший, ніж потрібно пошкодженню, бо він вийшов би без змін
    • -
    • - expected: accept поруч із пошкодженням, бо цьому не міг би відповідати жоден файл. - Пишіть sanitize, якщо тестована система має полагодити файл, або - unspecified, якщо саме це питання ви й ставите -
    • -
    -

    - Третє наперед дізнатися не можна. Якщо пошкодження виконується й не змінює жодного байта, такий файл - відкидається, а не записується - запуск триває, повідомляє, що це був за файл, і завершується - кодом часткового завершення. -

    -

    - Крок за кроком, з тестом, який читає маніфест: як зробити - пошкоджений файл для тестів. -

    +
    +

    Сторінки документації

    + {{ template "linkCards" .Docs }}
    -
    -

    Як виглядає рецепт?

    -

    - Рецепт - це файл YAML, що описує цілий запуск. Закомітьте його поряд із тестами, і фікстури - перестануть бути бінарними файлами у вашому репозиторії - будь-хто зможе відтворити їх байт у - байт із файлу в кілька сотень символів. -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - Кожній цілі потрібен рівно один із ключів size, size-range, - boundary або contains. Два - це помилка, і жодного - теж. Недійсний - рецепт записує жодного файлу і повідомляє про всі проблеми одразу, а не лише - про першу, щоразу називаючи налаштування, якого вона стосується. -

    +
    +

    Що робить інструмент, за темами

    + {{ template "linkCards" (.PagesOf "formats" "presets" "damage" "samples" "upload-tests" "ci" "exact-size") }}
    -
    -

    Як оголосити, що моя система має робити з файлом?

    -

    Коротка форма, коли досить результату, і довга, коли важлива причина:

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - Результати - accept, reject, sanitize і - unspecified. Причини утворюють закритий список, щоб звіт міг за ними групувати: - content_malformed, count_limit, dimensions_limit, - duplicate, encoding_invalid, extension_rule, - filename_invalid, filename_too_long, filename_traversal, - malware_signature, mime_mismatch, nesting_depth, - none, size_limit і size_zero. -

    -

    - Причина називає чинне правило, а не вердикт. Тому та сама причина може стояти під - будь-яким результатом - файл на байт менший за ліміт отримує accept, а правило, про - яке йдеться, усе одно size_limit. -

    -
    - -
    -

    Що в маніфесті?

    -

    - Він записується поряд із файлами наприкінці кожного запуску, зокрема й перерваного. Один запис на - файл: -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "{{ .Facts.Version }}" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - recipe_hash додається, якщо запуск був за рецептом, а preset з - overrides - якщо за пресетом, тож маніфест завжди можна простежити до того, що його - створило. -

    -

    - Кожен запис також містить target_id - id цілі рецепта, що створила файл, а - summary.by_target рахує файли кожної цілі. Рецепт із кількома цілями можна тому - перевірити ціль за ціллю, не читаючи імена файлів. -

    -
    - -
    -

    Що таке пресет?

    -

    - Готовий набір файлів, що відповідає на поширене тестове питання, щоб вам не доводилося проєктувати - набір самостійно. Пресети - звичайні рецепти всередині, а eject виводить рецепт, - щоб ви могли його відредагувати. Кожен пресет має окрему сторінку про - те, що він зазвичай знаходить, що входить у набір і які налаштування приймає. -

    - {{ template "presetsList" . }} -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show повідомляє, скільки коштував би набір, перш ніж ви його зберете, і прямо каже, - коли число - наша тимчасова підстановка, а не ваш ліміт. -

    -
    - -
    -

    Що означають коди завершення?

    -

    - Кожен кінець має власний код, машиночитний вивід іде в стандартний вивід, а невдалий запуск нічого - туди не друкує. Таблиця - заморожений контракт: зміна значення коду вимагає підвищення мажорної - версії. -

    - {{ template "exitCodesTable" . }} -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - Запуск, зупинений за допомогою Ctrl+C, усе одно залишає маніфест і ніколи не залишає наполовину - записаного файлу, тож скасоване завдання може бути прибране наступним. -

    -

    - Готові workflow для GitHub Actions і GitLab CI: як генерувати - тестові файли в конвеєрі CI. -

    -
    - -
    -

    Чи є десктопне вікно?

    -

    - Так, той самий рушій із вікном згори, для тестування, яке не автоматизується. Це не урізана версія: - тест порівнює два інтерфейси можливість за можливістю, і все, що вміє лише один із них, має бути - оголошене й обґрунтоване, а не тихо розходитися. -

    +
    +

    Досі не виходить?

    - Екрани: одна партія, пресети, кілька партій одночасно та про програму. Вікно показує, скільки - коштував би запуск, перш ніж щось записати, відображає перебіг роботи й може бути скасоване на - півдорозі без наполовину записаного файлу. Файл рецепта воно поки не відкриває - рецепти поки - справа командного рядка, а вікно збирає свої партії у формі. + tfg <command> --help показує в терміналі, що приймає команда. Кожна відмова називає налаштування, якого вона стосується, причину та значення, яке підійде. Якщо щось працює не так, як сказано на сторінці, повідомте про це. Це помилка сторінки або програми.

    diff --git a/web/content/uk/site.json b/web/content/uk/site.json index 97efb31f..729de746 100644 --- a/web/content/uk/site.json +++ b/web/content/uk/site.json @@ -138,7 +138,8 @@ "colSha256": "SHA-256", "colExpected": "Очікується", "colTool": "Інструмент", - "colQuestion": "На що відповідає" + "colQuestion": "На що відповідає", + "docsMenuLabel": "Сторінки документації" }, "endings": { "0": "Усе спрацювало.", @@ -386,5 +387,45 @@ "checksum": "Чи це той файл, за який він себе видає?", "checksum-check": "Чи відповідає кожен файл тому, що записано в його файлі контрольних сум?", "checksum-write": "Як я згодом дізнаюся, що жоден із цих файлів не змінився?" + }, + "docs": { + "guides": { + "guide-install": { + "title": "Встановлення", + "text": "Завантажити для Windows, macOS або Linux, перевірити архів або встановити через Docker, npm, pip чи Go." + }, + "guide-start": { + "title": "Перші кроки", + "text": "Перший файл точного розміру, потім десять тисяч, перевірені, видалені та записані як рецепт." + }, + "guide-commands": { + "title": "Команди", + "text": "Кожна команда й кожен прапорець зі значенням за замовчуванням, і всі коди завершення." + }, + "guide-recipes": { + "title": "Як писати рецепти", + "text": "Кожен ключ рецепта, розміри, імена файлів, очікувані реакції, пошкодження, архіви та пресети." + }, + "recipes": { + "title": "Галерея рецептів", + "text": "Готові рецепти для завантаження: вивантаження, імпорт, архіви, пошта, медіа, CI та масові файли." + }, + "guide-manifest": { + "title": "Маніфест", + "text": "Кожне поле manifest.json і те, як його читає тест." + }, + "guide-formats": { + "title": "Налаштування форматів", + "text": "Кожне налаштування кожного формату з допустимими значеннями та значенням за замовчуванням." + }, + "guide-frameworks": { + "title": "Тестові фреймворки", + "text": "Файли всередині pytest, Playwright, Vitest і node:test." + }, + "guide-window": { + "title": "Настільний застосунок", + "text": "Вікно програми, екран за екраном." + } + } } } diff --git a/web/content/vi/docs.html b/web/content/vi/docs.html index 796fe738..1dafae2f 100644 --- a/web/content/vi/docs.html +++ b/web/content/vi/docs.html @@ -1,278 +1,21 @@

    Tài liệu

    - Mọi thứ công cụ làm, sắp xếp theo những câu hỏi mà mọi người thật sự mang đến. - README trong kho mã là tài liệu tham chiếu đầy đủ và luôn khớp với - bản dựng bạn đã tải. + Cách cài đặt tfg, tạo những tệp kiểm thử đầu tiên, và mọi thứ chương trình nhận và ghi: mọi lệnh và mọi tùy chọn, mọi khóa của công thức, mọi trường của manifest và mọi thiết lập của mọi định dạng. Các trang này bằng tiếng Anh, vì chúng được tạo từ chính chương trình mỗi lần dựng trang web, nên luôn nói đúng những gì phiên bản bạn tải về làm.

    -
    -

    Có những lệnh nào?

    -

    Mỗi lệnh làm đúng một việc:

    - {{ template "commandList" . }} -

    - tfg tool chứa các công cụ cho tệp bạn đã có, chẳng hạn kiểm tra một tệp nén trước khi - giải nén. Công cụ mô tả từng công cụ. -

    -
    - -
    -

    Làm sao tạo một tệp đơn có kích thước chính xác?

    -

    - Nêu định dạng, kích thước và nơi đặt. Kích thước đếm theo 1024, nên 2mb là 2097152 - byte. Số byte thuần cũng được, nên --size 10485761 yêu cầu đúng chừng đó. -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    Các cờ hữu ích của generate:

    -
    - - - - - - - - - - - - - - - - - -
    CờTác dụng
    --format <id>định dạng của các tệp, ví dụ txt
    --size <size>kích thước chính xác của mỗi tệp, như 10mb hoặc số byte thuần
    --size-range <a-b>kích thước rút cho từng tệp từ một khoảng, như 1kb-8kb. Lần rút lấy từ seed
    --boundary <size>ba tệp quanh một giới hạn: thấp hơn một byte, đúng giới hạn, cao hơn một byte
    --count <n>tạo bao nhiêu tệp. Mặc định 1
    --name <template>mẫu tên, ví dụ invoice_{index:04}.txt
    --out <dir>thư mục để ghi vào
    --seed <n>seed của lần chạy. Cùng seed cho cùng các byte
    --set <k>=<v>một thiết lập định dạng, lặp lại được
    --damage <name>cố ý làm hỏng tệp, lặp lại được và áp dụng theo thứ tự. Chạy tfg damage để xem danh sách
    --expected <outcome>accept, reject, sanitize hoặc unspecified
    --dry-runđếm và hiển thị, hoàn toàn không ghi gì
    --jsonghi manifest ra đầu ra chuẩn
    -
    -
    - -
    -

    Làm sao tạo một tệp cố ý bị hỏng?

    -

    - Mọi tệp khác mà công cụ này ghi đều đúng theo cách xây dựng, điều đó trả lời hai trong ba câu hỏi mà - trình kiểm tra tải lên đặt ra. --damage trả lời câu thứ ba - tệp có mở được không. - Tệp được tạo bình thường rồi bị làm hỏng, nên nó vẫn có kích thước bạn đã yêu cầu. -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - Các thiết lập đặt sau dấu hai chấm. Cờ lặp lại được, và thứ tự bạn viết là thứ tự chúng được áp - dụng. tfg damage liệt kê những gì bản dựng này làm được và mỗi kiểu nhận gì. -

    -

    Trong công thức, khóa là một danh sách, gồm tên hoặc thiết lập:

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - Tệp bị làm hỏng nhận expected: reject trong manifest, kèm kiểu hỏng được ghi bên cạnh. - Hai thứ bị từ chối trước khi ghi bất cứ gì, vì mỗi thứ sẽ đặt lên đĩa một tệp mà manifest mô tả - sai: -

    -
      -
    • tệp nhỏ hơn mức kiểu hỏng cần, vì nó sẽ ra mà không thay đổi
    • -
    • - expected: accept bên cạnh một kiểu hỏng, vì không gì có thể đáp ứng. Hãy viết - sanitize nếu hệ thống được kiểm thử phải sửa tệp, hoặc unspecified - nếu đó chính là câu hỏi bạn đang đặt -
    • -
    -

    - Thứ ba không thể biết trước. Nếu một kiểu hỏng chạy mà không đổi byte nào, tệp đó bị bỏ thay vì được - ghi - lần chạy tiếp tục, nói đó là tệp nào và kết thúc bằng mã thoát một phần. -

    -

    - Từng bước, với một bài kiểm thử đọc manifest: cách tạo tệp bị - hỏng để kiểm thử. -

    +
    +

    Các trang tài liệu

    + {{ template "linkCards" .Docs }}
    -
    -

    Một công thức trông thế nào?

    -

    - Công thức là một tệp YAML mô tả cả một lần chạy. Hãy commit nó bên cạnh các bài kiểm thử và fixture - thôi là tệp nhị phân trong kho mã - ai cũng có thể dựng lại chúng, từng byte, từ một tệp vài - trăm ký tự. -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - Mỗi target cần đúng một trong size, size-range, boundary hoặc - contains. Hai cái là lỗi và không cái nào cũng là lỗi. Công thức không hợp lệ ghi - không tệp nào và báo mọi vấn đề cùng lúc thay vì chỉ cái đầu, mỗi cái nêu thiết - lập mà nó nói đến. -

    +
    +

    Công cụ làm gì, theo từng chủ đề

    + {{ template "linkCards" (.PagesOf "formats" "presets" "damage" "samples" "upload-tests" "ci" "exact-size") }}
    -
    -

    Làm sao khai báo hệ thống của tôi cần làm gì với một tệp?

    -

    Dạng ngắn khi kết quả là đủ, dạng dài khi lý do quan trọng:

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - Các kết quả là accept, reject, sanitize và - unspecified. Các lý do là một danh sách đóng để báo cáo có thể nhóm theo chúng: - content_malformed, count_limit, dimensions_limit, - duplicate, encoding_invalid, extension_rule, - filename_invalid, filename_too_long, filename_traversal, - malware_signature, mime_mismatch, nesting_depth, - none, size_limit và size_zero. -

    -

    - Một lý do nêu quy tắc đang áp dụng, không phải phán quyết. Vì vậy cùng một lý do có - thể nằm dưới cả hai kết quả - tệp thấp hơn giới hạn một byte là accept, và quy tắc - liên quan vẫn là size_limit. -

    -
    - -
    -

    Manifest chứa gì?

    -

    - Nó được ghi bên cạnh các tệp ở cuối mỗi lần chạy, kể cả lần chạy bị ngắt. Một mục cho mỗi tệp: -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "{{ .Facts.Version }}" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - recipe_hash được thêm khi lần chạy đến từ một công thức, và preset cùng - overrides khi nó đến từ một preset, nên manifest luôn truy ngược được về thứ đã tạo - ra nó. -

    -

    - Mỗi mục còn mang target_id, id của target trong công thức đã tạo tệp, và - summary.by_target đếm số tệp mà mỗi target tạo ra. Một công thức có nhiều target - nhờ vậy kiểm tra được từng target mà không cần đọc tên tệp. -

    -
    - -
    -

    Preset là gì?

    -

    - Một bộ tệp dựng sẵn trả lời một câu hỏi kiểm thử thường gặp, để bạn không phải tự thiết kế bộ. - Preset thực chất là công thức bình thường, và eject in công thức ra để bạn chỉnh - sửa từ đó. Mỗi preset có trang riêng nói nó thường tìm thấy gì, trong - bộ có gì và mọi thiết lập nó nhận. -

    - {{ template "presetsList" . }} -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show cho bạn biết bộ sẽ tốn bao nhiêu trước khi dựng, và nói thẳng khi một con số là - giá trị tạm của chúng tôi chứ không phải giới hạn của bạn. -

    -
    - -
    -

    Các mã thoát có nghĩa gì?

    -

    - Mỗi kết cục có mã riêng, đầu ra máy đọc được đi ra đầu ra chuẩn, và lần chạy thất bại không in gì ở - đó. Bảng này là một hợp đồng đóng băng - đổi nghĩa của một mã đòi hỏi tăng phiên bản chính. -

    - {{ template "exitCodesTable" . }} -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - Lần chạy bị dừng bằng Ctrl+C vẫn để lại manifest và không bao giờ để lại tệp ghi dở, nên tác vụ bị - hủy vẫn có thể được dọn bởi tác vụ sau. -

    -

    - Workflow có sẵn cho GitHub Actions và GitLab CI: cách tạo tệp - kiểm thử trong pipeline CI. -

    -
    - -
    -

    Có cửa sổ desktop không?

    -

    - Có, cùng một động cơ với một cửa sổ phủ lên, cho kiểu kiểm thử không viết kịch bản. Nó không phải - bản cắt giảm: một bài kiểm thử so sánh hai giao diện từng khả năng một, và bất cứ điều gì chỉ - một bên làm được đều phải được khai báo và biện minh thay vì lặng lẽ lệch nhau. -

    +
    +

    Vẫn còn vướng?

    - Các màn hình là một lô, preset, nhiều lô cùng lúc và giới thiệu. Nó cho biết một lần chạy sẽ tốn bao - nhiêu trước khi ghi gì, báo tiến độ khi đang chạy và có thể hủy giữa chừng mà không để lại tệp - ghi dở. Nó chưa mở được tệp công thức - hiện công thức là việc của dòng lệnh, còn cửa sổ dựng - các lô trong biểu mẫu. + tfg <command> --help cho biết trong terminal một lệnh nhận những gì. Mỗi lần từ chối đều nêu thiết lập liên quan, lý do và một giá trị sẽ dùng được. Nếu điều gì đó không hoạt động như một trang ở đây nói, hãy báo cho chúng tôi. Đó là lỗi của trang hoặc của chương trình.

    diff --git a/web/content/vi/site.json b/web/content/vi/site.json index e7424ab5..a872552b 100644 --- a/web/content/vi/site.json +++ b/web/content/vi/site.json @@ -138,7 +138,8 @@ "colSha256": "SHA-256", "colExpected": "Kỳ vọng", "colTool": "Công cụ", - "colQuestion": "Trả lời câu hỏi" + "colQuestion": "Trả lời câu hỏi", + "docsMenuLabel": "Các trang tài liệu" }, "endings": { "0": "Mọi thứ đều chạy tốt.", @@ -386,5 +387,45 @@ "checksum": "Tệp này có đúng là tệp mà nó tự nhận không?", "checksum-check": "Mọi tệp có còn đúng như tệp checksum của chúng ghi không?", "checksum-write": "Sau này làm sao tôi biết không có tệp nào trong số này thay đổi?" + }, + "docs": { + "guides": { + "guide-install": { + "title": "Cài đặt", + "text": "Tải về cho Windows, macOS hoặc Linux, kiểm tra tệp nén, hoặc cài bằng Docker, npm, pip hay Go." + }, + "guide-start": { + "title": "Bắt đầu", + "text": "Tệp đầu tiên đúng kích thước, rồi mười nghìn tệp, được kiểm tra, xóa đi và ghi lại thành công thức." + }, + "guide-commands": { + "title": "Lệnh", + "text": "Mọi lệnh và mọi tùy chọn cùng giá trị mặc định, và mọi mã thoát." + }, + "guide-recipes": { + "title": "Viết công thức", + "text": "Mọi khóa của công thức, kích thước, tên tệp, phản ứng mong đợi, hư hỏng, tệp nén và preset." + }, + "recipes": { + "title": "Thư viện công thức", + "text": "Công thức sẵn để tải cho tải lên, nhập dữ liệu, tệp nén, email, đa phương tiện, CI và tệp số lượng lớn." + }, + "guide-manifest": { + "title": "Manifest", + "text": "Mọi trường của manifest.json và cách một bài kiểm thử đọc nó." + }, + "guide-formats": { + "title": "Thiết lập định dạng", + "text": "Mọi thiết lập của mọi định dạng, với các giá trị được chấp nhận và giá trị mặc định." + }, + "guide-frameworks": { + "title": "Framework kiểm thử", + "text": "Các tệp bên trong pytest, Playwright, Vitest và node:test." + }, + "guide-window": { + "title": "Ứng dụng máy tính", + "text": "Cửa sổ chương trình, từng màn hình một." + } + } } } diff --git a/web/content/zh-Hans/docs.html b/web/content/zh-Hans/docs.html index 9984540d..85db553a 100644 --- a/web/content/zh-Hans/docs.html +++ b/web/content/zh-Hans/docs.html @@ -1,247 +1,21 @@

    文档

    - 工具的全部功能,按人们实际会问的问题来组织。仓库中的 README 是完整参考,并且始终与你下载的版本一致。 + 如何安装 tfg、生成第一批测试文件,以及程序接收和写出的一切:每个命令和每个参数、配方的每个键、清单的每个字段、每种格式的每个设置。这些页面是英文的,因为它们在每次构建网站时都由程序本身生成,所以始终与你下载的版本一致。

    -
    -

    有哪些命令?

    -

    每个命令只做一件事:

    - {{ template "commandList" . }} -

    - tfg tool 包含处理现有文件的工具,例如在解压前检查压缩包。工具介绍了其中每一个。 -

    -
    - -
    -

    如何生成一个大小精确的文件?

    -

    - 指定格式、大小和输出位置。大小按 1024 进制计算,所以 2mb 是 2097152 字节。直接写字节数也可以,所以 --size - 10485761 请求的就是恰好这么多。 -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    generate 常用的参数:

    -
    - - - - - - - - - - - - - - - - - -
    参数作用
    --format <id>文件格式,例如 txt
    --size <size>每个文件的精确大小,例如 10mb 或直接写字节数
    --size-range <a-b>从范围内为每个文件抽取一个大小,例如 1kb-8kb。抽取结果来自种子
    --boundary <size>围绕一个限制的三个文件:小一字节、恰好等于限制、大一字节
    --count <n>生成多少个文件。默认 1
    --name <template>文件名模板,例如 invoice_{index:04}.txt
    --out <dir>写入的目录
    --seed <n>本次运行的种子。相同的种子得到相同的字节
    --set <k>=<v>一项格式设置,可重复使用
    --damage <name>故意破坏文件,可重复使用,并按顺序应用。运行 tfg damage 查看列表
    --expected <outcome>accept、reject、sanitize 或 unspecified
    --dry-run只统计并显示,完全不写入
    --json将清单写到标准输出
    -
    -
    - -
    -

    如何做一个故意损坏的文件?

    -

    - 本工具写出的其他所有文件在构造上都是正确的,这回答了上传校验器会问的三个问题中的两个。--damage - 回答第三个,也就是文件到底能不能打开。文件先正常生成,再被破坏,因此仍然保持你请求的大小。 -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - 设置写在冒号后面。该参数可以重复,写入的顺序就是应用的顺序。tfg damage 会列出此版本能做什么,以及每种破坏接受哪些设置。 -

    -

    在配方中,这个键是一个列表,内容是名称或设置:

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - 受损文件在清单中会得到 expected: reject,并在旁边记录所做的破坏。有两种情况会在写入任何内容之前被拒绝,因为各自都会在磁盘上留下清单描述有误的文件: -

    -
      -
    • 文件小于破坏所需的大小,因为它会原样输出
    • -
    • - 在破坏旁边写 expected: accept,因为没有任何文件能满足它。如果被测系统应该修复该文件,请写 - sanitize,如果你问的正是这个问题,请写 unspecified -
    • -
    -

    - 第三种无法提前得知。如果某个破坏运行后没有改动任何字节,该文件会被丢弃而不是写出,运行会继续,指出是哪个文件,并以部分完成的退出码结束。 -

    -

    - 一步一步来,附带一个读取清单的测试:如何制作用于测试的损坏文件。 -

    +
    +

    文档页面

    + {{ template "linkCards" .Docs }}
    -
    -

    配方是什么样子?

    -

    - 配方是一个描述整次运行的 YAML 文件。把它与测试放在一起提交,fixture 就不再是仓库里的二进制文件,任何人都可以用一个只有几百个字符的文件逐字节重建它们。 -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - 每个 target 必须恰好有 size、size-range、boundary 或 - contains - 中的一个。两个是错误,一个都没有也是错误。无效的配方不会写入任何文件,并且会一次报告所有问题,而不是只报第一个,每个问题都会指明所涉及的设置。 -

    +
    +

    这个工具能做什么,按主题

    + {{ template "linkCards" (.PagesOf "formats" "presets" "damage" "samples" "upload-tests" "ci" "exact-size") }}
    -
    -

    如何声明我的系统应如何处理某个文件?

    -

    只需结果时用短写法,原因重要时用长写法:

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - 结果有 accept、reject、sanitize 和 - unspecified。原因是封闭列表,便于报告按原因分组:content_malformed、count_limit、dimensions_limit、duplicate、encoding_invalid、extension_rule、filename_invalid、filename_too_long、filename_traversal、malware_signature、mime_mismatch、nesting_depth、none、size_limit - 和 size_zero。 -

    -

    - 原因指明的是起作用的规则,而不是裁决。所以同一个原因可以出现在两种结果之下:比限制小一字节的文件是 accept,而它所涉及的规则仍然是 - size_limit。 -

    -
    - -
    -

    清单里有什么?

    -

    - 每次运行结束时,包括被中断的运行,它都会写在文件旁边。每个文件一项: -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "{{ .Facts.Version }}" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - 运行来自配方时会加上 recipe_hash,来自预设时会加上 preset 和 - overrides,因此清单总能追溯到产生它的来源。 -

    -

    - 每一项还带有 target_id,即配方中生成该文件的 target 的 id,summary.by_target 则统计每个 target - 生成的文件数。因此有多个 target 的配方可以逐个 target 检查,无需阅读文件名。 -

    -
    - -
    -

    什么是预设?

    -

    - 预设是回答常见测试问题的现成文件集,你不必自己设计。预设底层就是普通配方,eject - 会把配方打印出来,供你从那里开始编辑。每个预设都有自己的页面,说明它通常能发现什么、集合里有什么,以及它接受的每项设置。 -

    - {{ template "presetsList" . }} -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show 会在你构建之前告诉你这个集合的开销,并且在某个数字只是我们的占位值而不是你的限制时直接说明。 -

    -
    - -
    -

    退出码是什么意思?

    -

    - 每种结束方式都有自己的代码,机器可读的输出写到标准输出,失败的运行不会在那里打印任何内容。这张表是冻结的约定,改变某个代码的含义需要提升主版本号。 -

    - {{ template "exitCodesTable" . }} -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - 被 Ctrl+C 停止的运行仍会留下清单,也绝不会留下写了一半的文件,所以被取消的任务仍可由下一次运行清理。 -

    -

    - 适用于 GitHub Actions 和 GitLab CI 的现成工作流:如何在 CI 流水线中生成测试文件。 -

    -
    - -
    -

    有桌面窗口吗?

    -

    - 有,它就是在同一个引擎上加了一个窗口,用于不走脚本的测试。它不是缩水版:有测试逐项对比这两种界面,只有其中一方能做的事必须被声明并说明理由,而不是悄悄地渐行渐远。 -

    +
    +

    还是没解决?

    - 界面有单批生成、预设、同时多批和关于。它会在写入任何内容之前显示一次运行的开销,运行时报告进度,并且可以在中途取消而不会留下写了一半的文件。它目前还不能打开配方文件,配方暂时只属于命令行,窗口通过表单来构建批次。 + tfg <command> --help 会在终端里显示一个命令接收什么。每次拒绝都会说明涉及哪个设置、原因,以及一个可用的值。如果某个功能的表现与页面所说的不同,请告诉我们。那是页面或程序的错误。

    diff --git a/web/content/zh-Hans/site.json b/web/content/zh-Hans/site.json index 8e62b002..5114ae21 100644 --- a/web/content/zh-Hans/site.json +++ b/web/content/zh-Hans/site.json @@ -138,7 +138,8 @@ "colSha256": "SHA-256", "colExpected": "预期", "colTool": "工具", - "colQuestion": "回答的问题" + "colQuestion": "回答的问题", + "docsMenuLabel": "文档页面" }, "endings": { "0": "一切正常。", @@ -386,5 +387,45 @@ "checksum": "这个文件就是它声称的那个文件吗?", "checksum-check": "每个文件是否仍与校验和文件所记录的一致?", "checksum-write": "以后我怎么知道这些文件一个都没变?" + }, + "docs": { + "guides": { + "guide-install": { + "title": "安装", + "text": "下载适用于 Windows、macOS 或 Linux 的版本并校验压缩包,或通过 Docker、npm、pip、Go 安装。" + }, + "guide-start": { + "title": "入门", + "text": "先生成一个精确大小的文件,再生成一万个,校验、删除,并写成配方。" + }, + "guide-commands": { + "title": "命令", + "text": "每个命令和每个参数及其默认值,以及所有退出码。" + }, + "guide-recipes": { + "title": "编写配方", + "text": "配方的每个键、大小、文件名、预期反应、损坏、压缩包和预设。" + }, + "recipes": { + "title": "配方库", + "text": "可直接下载的配方,用于上传、导入、压缩包、邮件、媒体、CI 和大量文件。" + }, + "guide-manifest": { + "title": "清单", + "text": "manifest.json 的每个字段,以及测试如何读取它。" + }, + "guide-formats": { + "title": "格式设置", + "text": "每种格式的每个设置,包括可接受的值和默认值。" + }, + "guide-frameworks": { + "title": "测试框架", + "text": "在 pytest、Playwright、Vitest 和 node:test 中使用这些文件。" + }, + "guide-window": { + "title": "桌面应用", + "text": "逐个界面介绍程序窗口。" + } + } } } diff --git a/web/content/zh-Hant/docs.html b/web/content/zh-Hant/docs.html index a830912d..0be2e4b5 100644 --- a/web/content/zh-Hant/docs.html +++ b/web/content/zh-Hant/docs.html @@ -1,247 +1,21 @@

    文件

    - 工具的全部功能,依人們實際會問的問題來組織。儲存庫中的 README 是完整參考,並且始終與你下載的版本一致。 + 如何安裝 tfg、產生第一批測試檔案,以及程式接收與寫出的一切:每個指令與每個參數、配方的每個鍵、清單的每個欄位、每種格式的每個設定。這些頁面是英文的,因為它們在每次建置網站時都由程式本身產生,所以永遠與你下載的版本一致。

    -
    -

    有哪些指令?

    -

    每個指令只做一件事:

    - {{ template "commandList" . }} -

    - tfg tool 包含處理現有檔案的工具,例如在解壓縮前檢查壓縮檔。工具說明了其中每一個。 -

    -
    - -
    -

    如何產生一個大小精確的檔案?

    -

    - 指定格式、大小與輸出位置。大小以 1024 進位計算,所以 2mb 是 2097152 位元組。直接寫位元組數也可以,所以 --size - 10485761 要求的就是恰好這麼多。 -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    generate 常用的參數:

    -
    - - - - - - - - - - - - - - - - - -
    參數作用
    --format <id>檔案格式,例如 txt
    --size <size>每個檔案的精確大小,例如 10mb 或直接寫位元組數
    --size-range <a-b>從範圍內為每個檔案抽取一個大小,例如 1kb-8kb。抽取結果來自種子
    --boundary <size>圍繞一個限制的三個檔案:小一位元組、恰好等於限制、大一位元組
    --count <n>產生多少個檔案。預設 1
    --name <template>檔名範本,例如 invoice_{index:04}.txt
    --out <dir>寫入的目錄
    --seed <n>本次執行的種子。相同的種子得到相同的位元組
    --set <k>=<v>一項格式設定,可重複使用
    --damage <name>刻意破壞檔案,可重複使用,並依序套用。執行 tfg damage 查看清單
    --expected <outcome>accept、reject、sanitize 或 unspecified
    --dry-run只統計並顯示,完全不寫入
    --json將清單寫到標準輸出
    -
    -
    - -
    -

    如何做出刻意損壞的檔案?

    -

    - 本工具寫出的其他所有檔案在構造上都是正確的,這回答了上傳驗證器會問的三個問題中的兩個。--damage - 回答第三個,也就是檔案到底能不能開啟。檔案先正常產生,再被破壞,因此仍然維持你要求的大小。 -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - 設定寫在冒號後面。該參數可以重複,寫入的順序就是套用的順序。tfg damage 會列出此版本能做什麼,以及每種破壞接受哪些設定。 -

    -

    在配方中,這個鍵是一個清單,內容是名稱或設定:

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - 受損檔案在清單中會得到 expected: reject,並在旁邊記錄所做的破壞。有兩種情況會在寫入任何內容之前被拒絕,因為各自都會在磁碟上留下清單描述有誤的檔案: -

    -
      -
    • 檔案小於破壞所需的大小,因為它會原樣輸出
    • -
    • - 在破壞旁邊寫 expected: accept,因為沒有任何檔案能滿足它。如果受測系統應該修復該檔案,請寫 - sanitize,如果你問的正是這個問題,請寫 unspecified -
    • -
    -

    - 第三種無法事先得知。如果某個破壞執行後沒有改動任何位元組,該檔案會被捨棄而不是寫出,執行會繼續,指出是哪個檔案,並以部分完成的結束碼收尾。 -

    -

    - 一步一步來,附帶一個讀取清單的測試:如何製作用於測試的損毀檔案。 -

    +
    +

    文件頁面

    + {{ template "linkCards" .Docs }}
    -
    -

    配方長什麼樣子?

    -

    - 配方是一個描述整次執行的 YAML 檔案。把它與測試放在一起提交,fixture 就不再是儲存庫裡的二進位檔,任何人都可以用一個只有幾百個字元的檔案逐位元組重建它們。 -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - 每個 target 必須恰好有 size、size-range、boundary 或 - contains - 其中一個。兩個是錯誤,一個都沒有也是錯誤。無效的配方不會寫入任何檔案,並且會一次回報所有問題,而不是只報第一個,每個問題都會指明所涉及的設定。 -

    +
    +

    這個工具能做什麼,依主題

    + {{ template "linkCards" (.PagesOf "formats" "presets" "damage" "samples" "upload-tests" "ci" "exact-size") }}
    -
    -

    如何宣告我的系統應如何處理某個檔案?

    -

    只需結果時用簡短寫法,原因重要時用完整寫法:

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - 結果有 accept、reject、sanitize 與 - unspecified。原因是封閉清單,方便報告依原因分組:content_malformed、count_limit、dimensions_limit、duplicate、encoding_invalid、extension_rule、filename_invalid、filename_too_long、filename_traversal、malware_signature、mime_mismatch、nesting_depth、none、size_limit - 與 size_zero。 -

    -

    - 原因指明的是起作用的規則,而不是裁決。所以同一個原因可以出現在兩種結果之下:比限制小一位元組的檔案是 accept,而它所涉及的規則仍然是 - size_limit。 -

    -
    - -
    -

    清單裡有什麼?

    -

    - 每次執行結束時,包括被中斷的執行,它都會寫在檔案旁邊。每個檔案一項: -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "{{ .Facts.Version }}" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - 執行來自配方時會加上 recipe_hash,來自預設集時會加上 preset 與 - overrides,因此清單總能追溯到產生它的來源。 -

    -

    - 每一項還帶有 target_id,也就是配方中產生該檔案的 target 的 id,summary.by_target 則統計每個 target - 產生的檔案數。因此有多個 target 的配方可以逐個 target 檢查,無需閱讀檔名。 -

    -
    - -
    -

    什麼是預設集?

    -

    - 預設集是回答常見測試問題的現成檔案組,你不必自己設計。預設集底層就是普通配方,eject - 會把配方列印出來,供你從那裡開始編輯。每個預設集都有自己的頁面,說明它通常能發現什麼、組合裡有什麼,以及它接受的每項設定。 -

    - {{ template "presetsList" . }} -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show 會在你建置之前告訴你這個組合的開銷,並且在某個數字只是我們的預留值而不是你的限制時直接說明。 -

    -
    - -
    -

    結束碼是什麼意思?

    -

    - 每種結束方式都有自己的代碼,機器可讀的輸出寫到標準輸出,失敗的執行不會在那裡列印任何內容。這張表是凍結的約定,改變某個代碼的意義需要提升主版本號。 -

    - {{ template "exitCodesTable" . }} -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - 被 Ctrl+C 停止的執行仍會留下清單,也絕不會留下寫了一半的檔案,所以被取消的工作仍可由下一次執行清理。 -

    -

    - 適用於 GitHub Actions 和 GitLab CI 的現成工作流程:如何在 CI 流程中產生測試檔案。 -

    -
    - -
    -

    有桌面視窗嗎?

    -

    - 有,它就是在同一個引擎上加了一個視窗,用於不走腳本的測試。它不是縮水版:有測試逐項比對這兩種介面,只有其中一方能做的事必須被宣告並說明理由,而不是悄悄地漸行漸遠。 -

    +
    +

    還是沒有解決?

    - 畫面有單批產生、預設集、同時多批與關於。它會在寫入任何內容之前顯示一次執行的開銷,執行時回報進度,並且可以在中途取消而不會留下寫了一半的檔案。它目前還不能開啟配方檔,配方暫時只屬於命令列,視窗透過表單來建立批次。 + tfg <command> --help 會在終端機中顯示一個指令接收什麼。每次拒絕都會說明涉及哪個設定、原因,以及一個可用的值。如果某個功能的表現與頁面所說的不同,請告訴我們。那是頁面或程式的錯誤。

    diff --git a/web/content/zh-Hant/site.json b/web/content/zh-Hant/site.json index 27976265..17c1f1e9 100644 --- a/web/content/zh-Hant/site.json +++ b/web/content/zh-Hant/site.json @@ -138,7 +138,8 @@ "colSha256": "SHA-256", "colExpected": "預期", "colTool": "工具", - "colQuestion": "回答的問題" + "colQuestion": "回答的問題", + "docsMenuLabel": "文件頁面" }, "endings": { "0": "一切正常。", @@ -386,5 +387,45 @@ "checksum": "這個檔案就是它聲稱的那個檔案嗎?", "checksum-check": "每個檔案是否仍與總和檢查碼檔案所記錄的相符?", "checksum-write": "之後我要怎麼知道這些檔案一個都沒變?" + }, + "docs": { + "guides": { + "guide-install": { + "title": "安裝", + "text": "下載適用於 Windows、macOS 或 Linux 的版本並驗證壓縮檔,或透過 Docker、npm、pip、Go 安裝。" + }, + "guide-start": { + "title": "入門", + "text": "先產生一個精確大小的檔案,再產生一萬個,驗證、刪除,並寫成配方。" + }, + "guide-commands": { + "title": "指令", + "text": "每個指令與每個參數及其預設值,以及所有結束碼。" + }, + "guide-recipes": { + "title": "撰寫配方", + "text": "配方的每個鍵、大小、檔名、預期反應、損壞、壓縮檔與預設集。" + }, + "recipes": { + "title": "配方集", + "text": "可直接下載的配方,用於上傳、匯入、壓縮檔、電子郵件、媒體、CI 與大量檔案。" + }, + "guide-manifest": { + "title": "清單", + "text": "manifest.json 的每個欄位,以及測試如何讀取它。" + }, + "guide-formats": { + "title": "格式設定", + "text": "每種格式的每個設定,包括可接受的值與預設值。" + }, + "guide-frameworks": { + "title": "測試框架", + "text": "在 pytest、Playwright、Vitest 與 node:test 中使用這些檔案。" + }, + "guide-window": { + "title": "桌面應用程式", + "text": "逐一介紹程式視窗的每個畫面。" + } + } } } diff --git a/web/public/ar/docs/index.html b/web/public/ar/docs/index.html index 80862cf5..08057cdb 100644 --- a/web/public/ar/docs/index.html +++ b/web/public/ar/docs/index.html @@ -147,376 +147,93 @@

    التوثيق

    - كل ما تفعله الأداة، مرتبًا على هيئة الأسئلة التي يأتي بها الناس فعلًا. ملف - README في المستودع هو المرجع الكامل ويطابق دائمًا الإصدار الذي - نزّلته. + كيف تثبّت tfg، وتنشئ أول ملفات الاختبار، وكل ما يأخذه البرنامج ويكتبه: كل أمر وكل خيار، وكل مفتاح في الوصفة، وكل حقل في البيان، وكل إعداد لكل صيغة. هذه الصفحات باللغة الإنجليزية، لأنها تُبنى من البرنامج نفسه في كل مرة يُبنى فيها الموقع، لذلك تقول دائمًا ما يفعله الإصدار الذي تنزّله.

    -
    -

    ما الأوامر المتاحة؟

    -

    كل أمر يؤدي مهمة واحدة:

    -
    tfg generate    توليد ملفات، من وصفة أو من خيارات
    -tfg validate    فحص وصفة دون كتابة شيء
    -tfg verify      فحص مجلد مقابل بيان
    -tfg cleanup     حذف الملفات التي يسردها بيان
    -tfg recipe fmt  طباعة وصفة بشكلها المستقر
    -tfg preset      بناء مجموعة ملفات من سؤال اختبار مُسمّى
    -tfg formats     سرد الصيغ التي يدعمها هذا الإصدار
    -tfg damage      سرد الطرق التي يستطيع بها هذا الإصدار إتلاف ملف عمدًا
    -tfg tool        أدوات صغيرة للملفات التي لديك بالفعل
    -tfg version     طباعة إصدار الأداة
    -tfg license     طباعة الرخصة ومعناها للملفات المولَّدة
    -

    - يضم tfg tool أدوات للملفات الموجودة لديك، مثل فحص أرشيف قبل فك ضغطه. وتشرح صفحة - الأدوات كل واحدة منها. -

    -
    - -
    -

    كيف أولّد ملفًا واحدًا بحجم دقيق؟

    -

    - حدد الصيغة والحجم ووجهة الملف. تُعدّ الأحجام بالمضاعفات 1024، فـ2mb تساوي 2097152 - بايتًا. وعدد البايتات المجرد يصلح أيضًا، فـ--size 10485761 يطلب هذا العدد بالضبط. -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    الخيارات المفيدة في generate:

    -
    - - - - - - - - - - - - - - - - - -
    الخيارما يفعله
    --format <id>صيغة الملفات، مثل txt
    --size <size>الحجم الدقيق لكل ملف، مثل 10mb أو عدد بايتات مجرد
    --size-range <a-b>حجم يُسحب لكل ملف من نطاق، مثل 1kb-8kb. يأتي السحب من البذرة
    --boundary <size>ثلاثة ملفات حول حد: أقل بايتًا واحدًا، والحد نفسه، وأكثر بايتًا واحدًا
    --count <n>عدد الملفات المراد إنتاجها. الافتراضي 1
    --name <template>قالب الاسم، مثل invoice_{index:04}.txt
    --out <dir>المجلد الذي يُكتب فيه
    --seed <n>بذرة التشغيل. البذرة نفسها تعطي البايتات نفسها
    --set <k>=<v>إعداد صيغة، يمكن تكراره
    --damage <name>إتلاف الملفات عمدًا، يمكن تكراره ويُطبَّق بالترتيب. شغّل tfg damage للاطلاع على القائمة
    --expected <outcome>accept أو reject أو sanitize أو unspecified
    --dry-runعدّ وأظهر، ولا تكتب شيئًا إطلاقًا
    --jsonاكتب البيان إلى المخرج القياسي
    -
    -
    - -
    -

    كيف أصنع ملفًا تالفًا عمدًا؟

    -

    - كل ملف آخر تكتبه هذه الأداة صحيح بحكم بنائه، وهذا يجيب عن اثنين من ثلاثة أسئلة يطرحها مدقق الرفع. - أما --damage فيجيب عن الثالث: هل يُفتح الملف أصلًا. يُنتَج الملف بشكل طبيعي ثم - يُتلف، فيبقى بالحجم الذي طلبته. -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - تُكتب الإعدادات بعد نقطتين. يمكن تكرار الخيار، وترتيب كتابتها هو ترتيب تطبيقها. يسرد tfg - damage ما يستطيعه هذا الإصدار وما يقبله كل نوع. -

    -

    في الوصفة يكون المفتاح قائمة، من أسماء أو من إعدادات:

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - يحصل الملف التالف على expected: reject في البيان، مع تسجيل الإتلاف بجانبه. يُرفض أمران - قبل كتابة أي شيء، لأن كلًّا منهما كان سيضع على القرص ملفًا يصفه البيان وصفًا خاطئًا: -

    -
      -
    • ملف أصغر مما يحتاجه الإتلاف، لأنه كان سيخرج دون تغيير
    • -
    • - expected: accept بجانب إتلاف، لأن لا شيء يمكن أن يحققه. اكتب sanitize إن - كان المقصود أن يصلح النظام قيد الاختبار الملف، أو unspecified إن كان هذا هو - السؤال الذي تطرحه -
    • -
    -

    - أما الثالث فلا يمكن معرفته مسبقًا. إذا نُفّذ إتلاف ولم يحرّك أي بايت، يُسقَط ذلك الملف بدل كتابته، - ويستمر التشغيل ويذكر أي ملف كان، وينتهي برمز الخروج الجزئي. -

    -

    - خطوة بخطوة، مع اختبار يقرأ البيان: كيف تصنع ملفًا تالفًا - للاختبار. -

    -
    - -
    -

    كيف تبدو الوصفة؟

    -

    - الوصفة ملف YAML يصف تشغيلًا كاملًا. أودعها بجانب اختباراتك فتتوقف بيانات الاختبار عن كونها ملفات - ثنائية في مستودعك، ويستطيع أي شخص إعادة بنائها، بايتًا ببايت، من ملف بضع مئات من الأحرف. -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - يحتاج كل هدف إلى واحد فقط من size أو size-range أو boundary - أو contains. اثنان خطأ، وعدم وجود أي منها خطأ كذلك. الوصفة غير الصالحة لا - تكتب أي ملف وتبلّغ عن كل المشكلات دفعة واحدة لا عن أولها فقط، وتسمّي كل مشكلة الإعداد - الذي تخصه. -

    -
    - -
    -

    كيف أصرّح بما يجب أن يفعله نظامي بملف ما؟

    -

    الصيغة القصيرة حين تكفي النتيجة، والطويلة حين يهم السبب:

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - النتائج هي accept وreject وsanitize - وunspecified. الأسباب قائمة مغلقة ليتمكن التقرير من التجميع بحسبها: - content_malformed وcount_limit وdimensions_limit - وduplicate وencoding_invalid وextension_rule - وfilename_invalid وfilename_too_long وfilename_traversal - وmalware_signature وmime_mismatch وnesting_depth - وnone وsize_limit وsize_zero. -

    -

    - يسمّي السبب القاعدة المعنية لا الحكم. ولهذا يمكن أن يقع السبب نفسه تحت أي من - النتيجتين: ملف أقل من الحد بايتًا واحدًا نتيجته accept، والقاعدة المعنية تبقى - size_limit. -

    -
    - -
    -

    ماذا يوجد في البيان؟

    -

    - يُكتب بجانب الملفات في نهاية كل تشغيل، بما في ذلك التشغيل الذي أُوقف. عنصر واحد لكل ملف: -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "0.6.0-rc1" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - يُضاف recipe_hash حين يأتي التشغيل من وصفة، ويُضاف preset مع - overrides حين يأتي من إعداد مسبق، فيمكن دائمًا تتبّع البيان إلى ما أنتجه. -

    -

    - يحمل كل عنصر أيضًا target_id، وهو معرّف الهدف في الوصفة الذي أنتج الملف، ويحصي - summary.by_target الملفات التي انتهى إليها كل هدف. وهكذا يمكن فحص وصفة متعددة - الأهداف هدفًا هدفًا دون قراءة أسماء الملفات. -

    -
    - -
    -

    ما الإعداد المسبق؟

    -

    - مجموعة ملفات جاهزة تجيب عن سؤال اختبار شائع، فلا تحتاج إلى تصميم المجموعة بنفسك. الإعدادات المسبقة - وصفات عادية في جوهرها، ويطبع eject الوصفة لتعدّلها من هناك. لكل إعداد مسبق - صفحة خاصة تذكر ما يكتشفه عادةً، وما في المجموعة، وكل إعداد يقبله. -

    +
    +

    صفحات التوثيق

    • -

      الفارغ والأدنى

      -

      هل يمر ملف صالح بأصغر حجم تسمح به الصيغة؟

      -

      empty-and-minimal

      +

      التثبيت EN

      +

      نزّل لنظام Windows أو macOS أو Linux، وتحقق من الأرشيف، أو ثبّت عبر Docker أو npm أو pip أو Go.

    • -
    • -

      التعامل مع أسماء الملفات

      -

      هل سيخزّن نظامي ويعرض ويعيد اسم ملف لم يتوقعه؟

      -

      filename-handling

      +
    • +

      البدء EN

      +

      أول ملف بحجم دقيق، ثم عشرة آلاف ملف، تُفحص وتُحذف وتُكتب وصفةً.

    • -
    • -

      أحجام الصور

      -

      هل يقبل نظامي الصور بالأحجام التي تستخدمها الشاشات والمنصات؟

      -

      picture-sizes

      +
    • +

      الأوامر EN

      +

      كل أمر وكل خيار مع قيمته الافتراضية، وكل رموز الخروج.

      +
    • +
    • +

      كتابة الوصفات EN

      +

      كل مفتاح في الوصفة، والأحجام، وأسماء الملفات، وردود الفعل المتوقعة، والإتلاف، والأرشيفات، والإعدادات المسبقة.

    • -

      حدود الحجم

      -

      هل يُطبَّق حد الحجم تمامًا حيث أُعلن عنه؟

      -

      size-boundaries

      +

      معرض الوصفات EN

      +

      وصفات جاهزة للتنزيل للرفع والاستيراد والأرشيفات والبريد والوسائط وCI والملفات الكثيرة.

      +
    • +
    • +

      البيان EN

      +

      كل حقل في manifest.json وكيف يقرؤه الاختبار.

    • -

      استيراد الجداول

      -

      هل يصمد استيراد الجداول عندي أمام ما تصدّره الأدوات الحقيقية؟

      -

      tabular-import

      +

      إعدادات الصيغ EN

      +

      كل إعداد لكل صيغة، مع القيم المقبولة والقيمة الافتراضية.

    • -

      ترميز النص

      -

      هل يعرف قارئي ترميز الملف، أم يخمّن؟

      -

      text-encoding

      +

      أُطر الاختبار EN

      +

      الملفات داخل pytest وPlaywright وVitest وnode:test.

      +
    • +
    • +

      تطبيق سطح المكتب EN

      +

      نافذة البرنامج، شاشةً شاشة.

    • -

      التحقق من الرفع

      -

      هل يقبل نموذج الرفع عندي ما يجب قبوله ويرفض الباقي؟

      -

      upload-validation

      +

      الأدوات

      +

      أدوات تعمل دون اتصال للملفات الموجودة لديك: اعرف هل فك ضغط أرشيف ما آمن، بما في ذلك zip slip وzip bomb، وافحص المجاميع الاختبارية SHA-256 أو اكتبها.

    -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - يخبرك show بكلفة المجموعة قبل أن تبنيها، ويقول صراحةً حين يكون رقم ما قيمة مؤقتة منا لا - حدًّا منك. -

    -
    -

    ما معنى رموز الخروج؟

    -

    - لكل نهاية رمزها الخاص، وتذهب المخرجات المقروءة آليًا إلى المخرج القياسي، ولا يطبع التشغيل الفاشل - شيئًا هناك. الجدول عقد مجمّد، وتغيير معنى رمز يتطلب رفع الإصدار الرئيسي. -

    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    الرمزالمعنى
    0عمل كل شيء.
    1خطأ غير متوقع داخل الأداة.
    2أمر أو خيار خاطئ.
    3الوصفة غير صالحة.
    4لا تستطيع الصيغة فعل ما طُلب منها.
    5فشلت قراءة أو كتابة.
    6لا توجد مساحة كافية على القرص.
    7وجد verify عدم تطابق.
    8انتهى التشغيل لكن لم يُنتَج كل شيء.
    130أُوقف بواسطة Ctrl+C.
    143أوقفته إشارة، وهذا ما يبدو عليه انتهاء مهلة CI.
    -
    -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - التشغيل الموقوف بـ Ctrl+C يترك بيانًا ولا يترك أبدًا ملفًا مكتوبًا نصفه، لذا يمكن للمهمة التالية أن - تنظّف مهمة أُلغيت. -

    -

    - مسارات عمل جاهزة لـ GitHub Actions وGitLab CI: كيف تولّد ملفات - الاختبار في خط CI. -

    +
    +

    ما تفعله الأداة، حسب الموضوع

    +
      +
    • +

      الصيغ

      +

      كل صيغ الملفات التي يولّدها المولّد، وأصغر ملف ممكن لكل صيغة، والإعدادات التي تقبلها. تُفتح كل الصيغ الـ 32 في برامجها الأصلية.

      +
    • +
    • +

      الإعدادات المسبقة

      +

      مجموعات جاهزة من ملفات الاختبار، تجيب كل منها عن سؤال اختبار واحد: حدود الرفع، وأسماء الملفات، والترميزات، واستيراد الجداول، والملفات الفارغة، والتحقق.

      +
    • +
    • +

      ملفات تالفة

      +

      ملف أُتلف عمدًا بحجم دقيق، مع بيان يقول إن نظامك ينبغي أن يرفضه. لاختبار التحقق من الرفع والمحللات.

      +
    • +
    • +

      ملفات نموذجية

      +

      ملفات اختبار نموذجية للتنزيل: ملف من كل صيغة بحجم 1 MB، وملفات PDF وWord وExcel تالفة، وجداول CSV، وصور بديلة، ولكل ملف بصمة SHA-256.

      +
    • +
    • +

      حالات اختبار الرفع

      +

      حالات اختبار لرفع الملفات: حد الحجم، والملف الفارغ والتالف، والنوع الخاطئ، وأسماء الملفات غير المتوقعة، والأرشيفات، ومع كل حالة الملف الذي يختبرها.

      +
    • +
    • +

      ملفات الاختبار في CI

      +

      ولّد ملفات الاختبار في الخط بدل إيداع الملفات الثنائية: سير عمل GitHub Actions، ومهمة GitLab، ورموز الخروج، وفخ PowerShell.

      +
    • +
    • +

      الحجم الدقيق

      +

      fsutil وdd وtruncate وmkfile، كلٌّ منها مُقاس على نظامه، ولماذا لا يصلح ملف منشأ بهذه الطريقة عندما يحتاج الاختبار إلى PDF أو PNG.

      +
    • +
    -
    -

    هل توجد نافذة سطح مكتب؟

    -

    - نعم، المحرك نفسه بنافذة فوقه، للاختبار الذي لا يُكتب له سكربت. وهي ليست نسخة مبتورة: يقارن اختبار - الواجهتين ميزةً ميزة، وكل ما تستطيع إحداهما فعله دون الأخرى يجب أن يُعلَن ويُبرَّر بدل أن - يتباعدا بصمت. -

    +
    +

    ما زلت عالقًا؟

    - الشاشات هي دفعة واحدة، والإعدادات المسبقة، وعدة دفعات معًا، وحول. تُظهر كلفة التشغيل قبل كتابة أي - شيء، وتبلّغ عن التقدم أثناء العمل، ويمكن إلغاؤها في منتصف الطريق دون ترك ملف مكتوب نصفه. لا تفتح - ملف وصفة بعد، فالوصفات شأن سطر الأوامر حاليًا، وتبني النافذة دفعاتها في النموذج. + يعرض tfg <command> --help في الطرفية ما يأخذه الأمر. كل رفض يذكر الإعداد المعني والسبب وقيمة ستنجح. إذا تصرّف شيء بخلاف ما تقوله صفحة هنا، أخبرنا. فهذا خطأ في الصفحة أو في البرنامج.

    diff --git a/web/public/ar/tools/index.html b/web/public/ar/tools/index.html index 658cfcf0..8699edaf 100644 --- a/web/public/ar/tools/index.html +++ b/web/public/ar/tools/index.html @@ -151,6 +151,21 @@
    +

    التوثيق

    افحص الأرشيف قبل فك ضغطه، وتحقق من المجاميع الاختبارية

    diff --git a/web/public/assets/site.css b/web/public/assets/site.css index 6b90b60e..a892cb58 100644 --- a/web/public/assets/site.css +++ b/web/public/assets/site.css @@ -496,6 +496,67 @@ figcaption { margin-bottom: 0; } +/* ------------------------------------------------------ documentation menu */ + +/* The pages of the documentation, on every page under the hub. A row of short + * links that wraps, so a phone needs no script and no second layout. */ +.docsmenu { + margin: 0 0 32px; + padding-bottom: 16px; + border-bottom: 1px solid var(--border-soft); +} + +.docsmenu ul { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin: 0; + padding: 0; + list-style: none; +} + +.docsmenu a { + display: inline-block; + color: var(--text-dim); + text-decoration: none; + padding: 5px 10px; + border-radius: 8px; + font-size: 14px; + background: var(--surface); +} + +.docsmenu a:hover, +.docsmenu a[aria-current] { + color: var(--text); + background: var(--surface-3); +} + +/* Beside a link from a translated page to a page written in English only, so + * the reader knows before following it. */ +.tag { + display: inline-block; + margin-inline-start: 6px; + padding: 0 5px; + border: 1px solid var(--border); + border-radius: 4px; + font-size: 11px; + font-weight: 600; + letter-spacing: 0.04em; + color: var(--muted); + vertical-align: middle; +} + +/* A screen of the window on the page about it: real size on a wide screen, + * never wider than the column. */ +.shot img { + display: block; + width: 100%; + max-width: 560px; + height: auto; + border: 1px solid var(--border-soft); + border-radius: var(--radius); +} + /* ------------------------------------------------------------------- lists */ ul.plain { @@ -826,6 +887,15 @@ pre code { width: 100%; } + /* A file name or a command in a sentence can be wider than a phone, and a + * span that cannot break pushes the page sideways, the same as in a note. + * On a wide screen code keeps to one line. */ + main p code, + main li code { + white-space: normal; + overflow-wrap: anywhere; + } + .footer-inner { grid-template-columns: 1fr; gap: 26px; diff --git a/web/public/assets/window/presets.png b/web/public/assets/window/presets.png new file mode 100644 index 00000000..4bfa6546 Binary files /dev/null and b/web/public/assets/window/presets.png differ diff --git a/web/public/assets/window/several-batches.png b/web/public/assets/window/several-batches.png new file mode 100644 index 00000000..71924515 Binary files /dev/null and b/web/public/assets/window/several-batches.png differ diff --git a/web/public/assets/window/single-batch.png b/web/public/assets/window/single-batch.png new file mode 100644 index 00000000..78652cf8 Binary files /dev/null and b/web/public/assets/window/single-batch.png differ diff --git a/web/public/assets/window/tools.png b/web/public/assets/window/tools.png new file mode 100644 index 00000000..73ff4900 Binary files /dev/null and b/web/public/assets/window/tools.png differ diff --git a/web/public/corrupt-test-files/index.html b/web/public/corrupt-test-files/index.html index 6a776088..f82c04a1 100644 --- a/web/public/corrupt-test-files/index.html +++ b/web/public/corrupt-test-files/index.html @@ -394,7 +394,7 @@

    Where to go from here

    Test files in CI runs a recipe like this one in a pipeline.
  • - The documentation has every flag of tfg generate. + The page of commands has every flag of tfg generate.
  • diff --git a/web/public/cs/dokumentace/index.html b/web/public/cs/dokumentace/index.html index 17aa4df3..739e26a7 100644 --- a/web/public/cs/dokumentace/index.html +++ b/web/public/cs/dokumentace/index.html @@ -147,383 +147,93 @@

    Dokumentace

    - Vše, co nástroj dělá, uspořádané podle otázek, se kterými lidé skutečně přicházejí. - README v repozitáři je úplná reference a vždy odpovídá verzi, - kterou jste stáhli. + Jak nainstalovat tfg, vytvořit první testovací soubory a vše, co program přijímá a zapisuje: každý příkaz a každý přepínač, každý klíč receptu, každé pole manifestu a každé nastavení každého formátu. Tyto stránky jsou v angličtině, protože vznikají přímo z programu při každém sestavení webu, a proto vždy říkají, co dělá verze, kterou stahujete.

    -
    -

    Jaké příkazy existují?

    -

    Každý dělá jednu věc:

    -
    tfg generate    vytvořit soubory z receptu nebo z přepínačů
    -tfg validate    zkontrolovat recept a nic nezapisovat
    -tfg verify      zkontrolovat adresář proti manifestu
    -tfg cleanup     odstranit soubory, které manifest uvádí
    -tfg recipe fmt  vypsat recept v ustáleném tvaru
    -tfg preset      sestavit sadu souborů z pojmenované testovací otázky
    -tfg formats     vypsat formáty, které tato verze podporuje
    -tfg damage      vypsat způsoby, jak tato verze umí soubor schválně poškodit
    -tfg tool        drobné pomůcky pro soubory, které už máte
    -tfg version     vypsat verzi nástroje
    -tfg license     vypsat licenci a co znamená pro generované soubory
    -

    - tfg tool obsahuje nástroje pro soubory, které už máte, například kontrolu archivu před - rozbalením. Nástroje popisují každý z nich. -

    -
    - -
    -

    Jak vygeneruji jeden soubor přesné velikosti?

    -

    - Uveďte formát, velikost a kam soubor půjde. Velikosti se počítají po 1024, takže 2mb je - 2097152 bajtů. Funguje i prostý počet bajtů, takže --size 10485761 žádá přesně - tolik. -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    Užitečné přepínače příkazu generate:

    -
    - - - - - - - - - - - - - - - - - -
    PřepínačCo dělá
    --format <id>formát souborů, například txt
    --size <size>přesná velikost každého souboru, například 10mb nebo prostý počet bajtů
    --size-range <a-b>velikost losovaná pro každý soubor z rozsahu, například 1kb-8kb. Losování vychází ze seedu
    --boundary <size>tři soubory kolem limitu: o bajt pod, limit, o bajt nad
    --count <n>kolik souborů vytvořit. Výchozí 1
    --name <template>šablona názvu, například invoice_{index:04}.txt
    --out <dir>adresář, do kterého se zapisuje
    --seed <n>seed běhu. Stejný seed dává stejné bajty
    --set <k>=<v>nastavení formátu, lze opakovat
    --damage <name>záměrně soubory poškodit, lze opakovat a uplatňuje se v pořadí. Seznam získáte příkazem tfg damage
    --expected <outcome>accept, reject, sanitize nebo unspecified
    --dry-runspočítat a ukázat, nic nezapisovat
    --jsonzapsat manifest na standardní výstup
    -
    -
    - -
    -

    Jak vytvořím soubor, který je záměrně rozbitý?

    -

    - Každý jiný soubor, který tento nástroj zapíše, je správný z konstrukce, což odpovídá na dvě ze tří - otázek, které klade validátor nahrávání. --damage odpovídá na třetí - zda se soubor - vůbec otevře. Soubor se vytvoří normálně a pak se rozbije, takže má stále velikost, o kterou - jste požádali. -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - Nastavení se zadávají za dvojtečku. Přepínač se opakuje a pořadí, v jakém je napíšete, je pořadí, v - jakém se uplatní. tfg damage vypíše, co tato verze umí a co která varianta přijímá. -

    -

    V receptu je klíč seznam, a to názvů nebo nastavení:

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - Poškozený soubor dostane v manifestu expected: reject a vedle toho zaznamenané - poškození. Dvě věci jsou odmítnuty dříve, než se cokoli zapíše, protože každá by jinak dala na - disk soubor, který manifest popisuje špatně: -

    -
      -
    • soubor menší, než poškození potřebuje, protože by vyšel beze změny
    • -
    • - expected: accept vedle poškození, protože nic by to nemohlo splnit. Napište - sanitize, pokud má testovaný systém soubor opravit, nebo - unspecified, pokud je to právě ta otázka, kterou kladete -
    • -
    -

    - Třetí se předem zjistit nedá. Pokud se poškození provede a nepohne žádným bajtem, soubor se zahodí - místo zapsání - běh pokračuje, řekne, o který soubor šlo, a skončí s částečným návratovým kódem. -

    -

    - Krok za krokem, s testem, který čte manifest: jak - vytvořit poškozený soubor pro testy. -

    -
    - -
    -

    Jak vypadá recept?

    -

    - Recept je soubor YAML popisující celý běh. Commitujte ho vedle testů a fixtures přestanou být - binárkami ve vašem repozitáři - kdokoli je může bajt po bajtu znovu sestavit ze souboru o - několika stovkách znaků. -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - Každý target potřebuje přesně jeden z klíčů size, size-range, - boundary nebo contains. Dva jsou chyba a žádný také. Neplatný recept - nezapíše žádné soubory a nahlásí všechny problémy najednou, ne jen první, každý - s názvem nastavení, kterého se týká. -

    -
    - -
    -

    Jak deklaruji, co má můj systém se souborem udělat?

    -

    Krátká forma, když stačí výsledek, dlouhá forma, když záleží na důvodu:

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - Výsledky jsou accept, reject, sanitize a - unspecified. Důvody tvoří uzavřený seznam, aby podle nich mohl report seskupovat: - content_malformed, count_limit, dimensions_limit, - duplicate, encoding_invalid, extension_rule, - filename_invalid, filename_too_long, filename_traversal, - malware_signature, mime_mismatch, nesting_depth, - none, size_limit a size_zero. -

    -

    - Důvod pojmenovává pravidlo, o které jde, ne verdikt. Proto může stejný důvod stát - pod oběma výsledky - soubor o bajt pod limitem je accept a pravidlo, o které jde, - je stále size_limit. -

    -
    - -
    -

    Co obsahuje manifest?

    -

    - Zapisuje se vedle souborů na konci každého běhu, včetně přerušeného. Jedna položka na soubor: -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "0.6.0-rc1" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - recipe_hash se přidá, když běh pochází z receptu, a preset s - overrides, když pochází z předvolby, takže manifest lze vždy dohledat k tomu, co ho - vytvořilo. -

    -

    - Každá položka nese také target_id, id targetu v receptu, který soubor vytvořil, a - summary.by_target počítá soubory, ke kterým každý target dospěl. Recept s více - targety lze tak kontrolovat target po targetu, aniž by se četly názvy souborů. -

    -
    - -
    -

    Co je předvolba?

    -

    - Hotová sada souborů, která odpovídá na běžnou testovací otázku, abyste sadu nemuseli navrhovat sami. - Předvolby jsou pod povrchem obyčejné recepty a eject recept vypíše, takže ho můžete - odtud upravit. Každá předvolba má vlastní stránku s tím, co obvykle - najde, co je v sadě a jaké nastavení přijímá. -

    +
    +

    Stránky dokumentace

    • -

      Prázdné a minimální

      -

      Projde platný soubor tak malý, jak formát dovolí?

      -

      empty-and-minimal

      +

      Instalace EN

      +

      Stažení pro Windows, macOS nebo Linux, kontrola archivu, nebo instalace přes Docker, npm, pip či Go.

    • -
    • -

      Zacházení s názvy souborů

      -

      Uloží, zobrazí a vrátí můj systém název souboru, který nečekal?

      -

      filename-handling

      +
    • +

      První kroky EN

      +

      První soubor přesné velikosti, potom deset tisíc, zkontrolované, smazané a zapsané jako recept.

    • -
    • -

      Velikosti obrázků

      -

      Přijme můj systém obrázky ve velikostech, které používají obrazovky a platformy?

      -

      picture-sizes

      +
    • +

      Příkazy EN

      +

      Každý příkaz a každý přepínač s výchozí hodnotou a všechny návratové kódy.

      +
    • +
    • +

      Psaní receptů EN

      +

      Každý klíč receptu, velikosti, názvy souborů, očekávané reakce, poškození, archivy a presety.

    • -

      Hranice velikosti

      -

      Je limit velikosti vynucován přesně tam, kde je deklarován?

      -

      size-boundaries

      +

      Galerie receptů EN

      +

      Hotové recepty ke stažení pro nahrávání, importy, archivy, e-maily, média, CI a hromadné soubory.

      +
    • +
    • +

      Manifest EN

      +

      Každé pole manifest.json a jak ho test čte.

    • -

      Import tabulek

      -

      Přežije můj import tabulek to, co exportují skutečné nástroje?

      -

      tabular-import

      +

      Nastavení formátů EN

      +

      Každé nastavení každého formátu s povolenými hodnotami a výchozí hodnotou.

    • -

      Kódování textu

      -

      Ví moje čtečka, v jakém kódování soubor je, nebo hádá?

      -

      text-encoding

      +

      Testovací frameworky EN

      +

      Soubory v pytest, Playwright, Vitest a node:test.

      +
    • +
    • +

      Desktopová aplikace EN

      +

      Okno programu, obrazovka po obrazovce.

    • -

      Validace nahrávání

      -

      Přijme můj formulář pro nahrávání to, co má, a zbytek odmítne?

      -

      upload-validation

      +

      Nástroje

      +

      Offline nástroje pro soubory, které už máte: zda je bezpečné rozbalit archiv, včetně zip slip a zip bomb, a kontrola nebo zápis kontrolních součtů SHA-256.

    -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show vám řekne, kolik by sada stála, než ji sestavíte, a otevřeně řekne, když je číslo - naším zástupným údajem, a ne vaším limitem. -

    -
    -

    Co znamenají návratové kódy?

    -

    - Každý konec má svůj kód, strojově čitelný výstup jde na standardní výstup a neúspěšný běh tam - nevypíše nic. Tabulka je zmrazená smlouva - změna významu kódu vyžaduje novou hlavní verzi. -

    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    KódVýznam
    0Vše fungovalo.
    1Neočekávaná chyba uvnitř nástroje.
    2Špatný příkaz nebo přepínač.
    3Recept není platný.
    4Formát neumí to, co bylo požadováno.
    5Čtení nebo zápis selhal.
    6Nedostatek místa na disku.
    7verify našel nesrovnalost.
    8Běh skončil, ale nebylo vytvořeno všechno.
    130Přerušeno pomocí Ctrl+C.
    143Zastaveno signálem, tak vypadá vypršení času v CI.
    -
    -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - Běh zastavený pomocí Ctrl+C po sobě stále zanechá manifest a nikdy nenechá napůl zapsaný soubor, - takže zrušenou úlohu může následující stále uklidit. -

    -

    - Hotová workflow pro GitHub Actions a GitLab CI: jak generovat - testovací soubory v CI pipeline. -

    +
    +

    Co nástroj dělá, podle témat

    +
      +
    • +

      Formáty

      +

      Všechny formáty, které generátor vytváří, nejmenší možný soubor každého z nich a jejich nastavení. Všech 32 se otevře ve svém programu.

      +
    • +
    • +

      Předvolby

      +

      Hotové sady testovacích souborů, každá odpovídá na jednu otázku: limity nahrávání, názvy souborů, kódování, import tabulek, prázdné soubory a validace.

      +
    • +
    • +

      Poškozené soubory

      +

      Soubor záměrně rozbitý, přesné velikosti, s manifestem, který říká, že ho má váš systém odmítnout. Pro testování validace nahrávání a parserů.

      +
    • +
    • +

      Ukázkové soubory

      +

      Testovací soubory ke stažení: jeden od každého formátu po 1 MB, poškozené soubory PDF, Word a Excel, tabulky CSV a zástupné obrázky, každý se součtem SHA-256.

      +
    • +
    • +

      Testovací případy nahrávání

      +

      Testovací případy nahrávání souborů: limit velikosti, prázdné a poškozené soubory, špatný typ, nečekané názvy a archivy, každý se souborem, který ho testuje.

      +
    • +
    • +

      Testovací soubory v CI

      +

      Generujte testovací soubory v pipeline místo commitování binárek: workflow pro GitHub Actions, job v GitLabu, návratové kódy a past PowerShellu.

      +
    • +
    • +

      Přesná velikost

      +

      fsutil, dd, truncate a mkfile, každý změřený na svém systému, a proč takto vytvořený soubor není PDF ani PNG, když to test potřebuje.

      +
    • +
    -
    -

    Existuje desktopové okno?

    -

    - Ano, stejný motor s oknem navrch, pro testování, které se neskriptuje. Není to osekaná verze: test - porovnává obě rozhraní schopnost po schopnosti a cokoli, co umí jen jedno z nich, musí být - deklarováno a zdůvodněno, ne tiše se rozcházet. -

    +
    +

    Stále si nevíte rady?

    - Obrazovky jsou jedna dávka, předvolby, více dávek najednou a O aplikaci. Ukáže, kolik by běh stál, - než cokoli zapíše, hlásí průběh a lze ho zrušit uprostřed, aniž by zanechal napůl zapsaný - soubor. Soubor receptu zatím neotevře - recepty jsou zatím záležitostí příkazového řádku a okno - sestavuje své dávky ve formuláři. + tfg <command> --help v terminálu řekne, co příkaz přijímá. Každé odmítnutí jmenuje nastavení, kterého se týká, důvod a hodnotu, která bude fungovat. Pokud se něco chová jinak, než říká stránka, nahlaste to. Jde o chybu stránky nebo programu.

    diff --git a/web/public/cs/nastroje/index.html b/web/public/cs/nastroje/index.html index bb66a5fa..94d998d7 100644 --- a/web/public/cs/nastroje/index.html +++ b/web/public/cs/nastroje/index.html @@ -151,6 +151,21 @@
    +

    Dokumentace

    Kontrola archivu před rozbalením a ověření kontrolních součtů

    diff --git a/web/public/de/dokumentation/index.html b/web/public/de/dokumentation/index.html index 75e073f0..3ebedd00 100644 --- a/web/public/de/dokumentation/index.html +++ b/web/public/de/dokumentation/index.html @@ -147,392 +147,93 @@

    Dokumentation

    - Alles, was das Tool kann, geordnet nach den Fragen, mit denen die Leute tatsächlich kommen. Die - README im Repository ist die vollständige Referenz und passt immer - zu dem Build, den du heruntergeladen hast. + Wie Sie tfg installieren, Ihre ersten Testdateien erzeugen und alles, was das Programm annimmt und schreibt: jeder Befehl und jede Option, jeder Schlüssel eines Rezepts, jedes Feld des Manifests und jede Einstellung jedes Formats. Diese Seiten sind auf Englisch, weil sie bei jedem Bau der Website aus dem Programm selbst entstehen und deshalb immer sagen, was die Version tut, die Sie herunterladen.

    -
    -

    Welche Befehle gibt es?

    -

    Jeder tut genau eine Sache:

    -
    tfg generate    Dateien erzeugen, aus einem Rezept oder über Flags
    -tfg validate    ein Rezept prüfen und nichts schreiben
    -tfg verify      ein Verzeichnis gegen ein Manifest prüfen
    -tfg cleanup     die Dateien entfernen, die ein Manifest auflistet
    -tfg recipe fmt  ein Rezept in seiner festen Form ausgeben
    -tfg preset      ein Set von Dateien aus einer benannten Testfrage erzeugen
    -tfg formats     die Formate dieses Builds auflisten
    -tfg damage      die Arten auflisten, wie dieser Build eine Datei absichtlich beschädigen kann
    -tfg tool        kleine Helfer für Dateien, die du schon hast
    -tfg version     die Version des Tools ausgeben
    -tfg license     die Lizenz ausgeben und was sie für erzeugte Dateien bedeutet
    -

    - tfg tool enthält die Werkzeuge für Dateien, die du schon hast, etwa die Prüfung eines - Archivs vor dem Entpacken. Die Seite Werkzeuge beschreibt jedes davon. -

    -
    - -
    -

    Wie erzeuge ich eine einzelne Datei in exakter Größe?

    -

    - Nenne das Format, die Größe und das Ziel. Größen zählen in 1024ern, 2mb sind also - 2097152 Bytes. Eine einfache Byte-Zahl funktioniert auch, --size 10485761 verlangt - also genau so viele. -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    Die nützlichen Flags von generate:

    -
    - - - - - - - - - - - - - - - - - -
    FlagWas es tut
    --format <id>Format der Dateien, zum Beispiel txt
    --size <size>exakte Größe jeder Datei, etwa 10mb oder eine einfache Byte-Zahl
    --size-range <a-b>eine Größe, die pro Datei aus einem Bereich gezogen wird, etwa 1kb-8kb. Die Ziehung kommt aus dem Seed
    --boundary <size>drei Dateien rund um ein Limit: ein Byte darunter, das Limit, ein Byte darüber
    --count <n>wie viele Dateien erzeugt werden. Standard 1
    --name <template>Namensvorlage, zum Beispiel invoice_{index:04}.txt
    --out <dir>Verzeichnis, in das geschrieben wird
    --seed <n>Seed des Laufs. Derselbe Seed ergibt dieselben Bytes
    --set <k>=<v>eine Formateinstellung, wiederholbar
    --damage <name>Dateien absichtlich beschädigen, wiederholbar und der Reihe nach angewendet. Mit tfg damage bekommst du die Liste
    --expected <outcome>accept, reject, sanitize oder unspecified
    --dry-runzählen und anzeigen, überhaupt nichts schreiben
    --jsondas Manifest auf die Standardausgabe schreiben
    -
    -
    - -
    -

    Wie erzeuge ich eine absichtlich kaputte Datei?

    -

    - Jede andere Datei, die dieses Tool schreibt, ist per Konstruktion korrekt, was zwei der drei Fragen - beantwortet, die ein Upload-Validator stellt. --damage beantwortet die dritte - - lässt sich die Datei überhaupt öffnen. Die Datei wird normal erzeugt und dann beschädigt, sie - hat also weiterhin die verlangte Größe. -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - Einstellungen stehen hinter einem Doppelpunkt. Das Flag lässt sich wiederholen, und die Reihenfolge, - in der du sie schreibst, ist die Reihenfolge, in der sie angewendet werden. tfg - damage listet auf, was dieser Build kann und was jede Variante annimmt. -

    -

    In einem Rezept ist der Schlüssel eine Liste, aus Namen oder aus Einstellungen:

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - Eine beschädigte Datei bekommt im Manifest expected: reject, mit der daneben - festgehaltenen Beschädigung. Zwei Dinge werden abgelehnt, bevor etwas geschrieben wird, weil - sonst jeweils eine Datei auf die Platte käme, die das Manifest falsch beschreibt: -

    -
      -
    • eine Datei, die kleiner ist, als die Beschädigung braucht, weil sie unverändert herauskäme
    • -
    • - expected: accept neben einer Beschädigung, weil es keine Datei geben kann, die das - erfüllt. Schreibe sanitize, wenn das getestete System die Datei reparieren soll, - oder unspecified, wenn genau das die Frage ist, die du stellst -
    • -
    -

    - Eine dritte lässt sich nicht im Voraus wissen. Wenn eine Beschädigung läuft und kein Byte verändert, - wird diese Datei verworfen statt geschrieben - der Lauf macht weiter, sagt, um welche Datei es - ging, und endet mit dem Exit-Code für teilweise erfolgreiche Läufe. -

    -

    - Schritt für Schritt, mit einem Test, der das Manifest liest: - So erzeugen Sie eine beschädigte Datei zum Testen. -

    -
    - -
    -

    Wie sieht ein Rezept aus?

    -

    - Ein Rezept ist eine YAML-Datei, die einen ganzen Lauf beschreibt. Checke sie neben deinen Tests ein, - und die Fixtures sind keine Binärdateien mehr in deinem Repository - jeder kann sie Byte für - Byte aus einer Datei von wenigen hundert Zeichen neu erzeugen. -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - Jedes Target braucht genau eines von size, size-range, - boundary oder contains. Zwei davon sind ein Fehler, und keines - ebenfalls. Ein ungültiges Rezept schreibt überhaupt keine Dateien und meldet - alle Probleme auf einmal statt nur das erste, jedes mit der Einstellung, um die es geht. -

    -
    - -
    -

    Wie lege ich fest, was mein System mit einer Datei tun soll?

    -

    Kurzform, wenn das Ergebnis reicht, Langform, wenn der Grund zählt:

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - Die Ergebnisse sind accept, reject, sanitize und - unspecified. Die Gründe sind eine geschlossene Liste, damit ein Report danach - gruppieren kann: content_malformed, count_limit, - dimensions_limit, duplicate, encoding_invalid, - extension_rule, filename_invalid, filename_too_long, - filename_traversal, malware_signature, mime_mismatch, - nesting_depth, none, size_limit und - size_zero. -

    -

    - Ein Grund benennt die Regel, um die es geht, nicht das Urteil. Deshalb kann - derselbe Grund unter beiden Ergebnissen stehen - eine Datei ein Byte unter einem Limit ist - accept, und die Regel, um die es geht, ist trotzdem size_limit. -

    -
    - -
    -

    Was steht im Manifest?

    -

    - Es wird am Ende jedes Laufs neben die Dateien geschrieben, auch bei einem unterbrochenen Lauf. Ein - Eintrag pro Datei: -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "0.6.0-rc1" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - Ein recipe_hash kommt hinzu, wenn der Lauf aus einem Rezept stammt, und - preset mit overrides, wenn er aus einem Preset stammt, sodass sich ein - Manifest immer auf das zurückführen lässt, was es erzeugt hat. -

    -

    - Jeder Eintrag trägt außerdem target_id, die ID des Targets im Rezept, das die Datei - erzeugt hat, und summary.by_target zählt, auf wie viele Dateien jedes Target kam. - Ein Rezept mit mehreren Targets lässt sich so Target für Target prüfen, ohne Dateinamen zu - lesen. -

    -
    - -
    -

    Was ist ein Preset?

    -

    - Ein fertiges Set aus Dateien, das eine gängige Testfrage beantwortet, damit du das Set nicht selbst - entwerfen musst. Presets sind darunter ganz normale Rezepte, und eject gibt das - Rezept aus, damit du es von dort aus bearbeiten kannst. Jedes Preset hat - eine eigene Seite mit dem, was es meist findet, was im Set steckt und - welche Einstellungen es kennt. -

    +
    +

    Seiten der Dokumentation

    • -

      Leer und minimal

      -

      Kommt eine gültige Datei durch, die so klein ist, wie das Format es erlaubt?

      -

      empty-and-minimal

      +

      Installation EN

      +

      Für Windows, macOS oder Linux herunterladen, das Archiv prüfen oder mit Docker, npm, pip oder Go installieren.

    • -
    • -

      Umgang mit Dateinamen

      -

      Speichert, zeigt und liefert mein System einen Dateinamen korrekt, mit dem es nicht gerechnet hat?

      -

      filename-handling

      +
    • +

      Erste Schritte EN

      +

      Die erste Datei mit exakter Größe, dann zehntausend, geprüft, entfernt und als Rezept festgehalten.

    • -
    • -

      Bildgrößen

      -

      Nimmt mein System Bilder in den Größen an, die Bildschirme und Plattformen verwenden?

      -

      picture-sizes

      +
    • +

      Befehle EN

      +

      Jeder Befehl und jede Option mit ihrem Standardwert, dazu alle Exit-Codes.

      +
    • +
    • +

      Rezepte schreiben EN

      +

      Jeder Schlüssel eines Rezepts, Größen, Dateinamen, erwartete Reaktionen, Beschädigungen, Archive und Presets.

    • -

      Größengrenzen

      -

      Wird ein Größenlimit genau dort durchgesetzt, wo es angegeben ist?

      -

      size-boundaries

      +

      Rezeptsammlung EN

      +

      Fertige Rezepte zum Herunterladen für Uploads, Importe, Archive, E-Mails, Medien, CI und Massendateien.

      +
    • +
    • +

      Manifest EN

      +

      Jedes Feld von manifest.json und wie ein Test es liest.

    • -

      Tabellenimport

      -

      Übersteht mein Tabellenimport das, was echte Tools exportieren?

      -

      tabular-import

      +

      Formateinstellungen EN

      +

      Jede Einstellung jedes Formats mit den erlaubten Werten und dem Standardwert.

    • -

      Textkodierung

      -

      Weiß mein Leser, in welcher Kodierung eine Datei vorliegt, oder rät er?

      -

      text-encoding

      +

      Test-Frameworks EN

      +

      Die Dateien in pytest, Playwright, Vitest und node:test.

      +
    • +
    • +

      Desktop-Anwendung EN

      +

      Das Fenster, Bildschirm für Bildschirm.

    • -

      Upload-Validierung

      -

      Nimmt mein Upload-Formular an, was es soll, und weist den Rest ab?

      -

      upload-validation

      +

      Werkzeuge

      +

      Offline-Werkzeuge für vorhandene Dateien: prüfen, ob ein Archiv sicher zu entpacken ist, samt Zip Slip und Zip-Bombe, und SHA-256-Summen prüfen oder schreiben.

    -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show sagt dir, was das Set kosten würde, bevor du es baust, und sagt - unmissverständlich, wenn eine Zahl ein Platzhalter von uns statt ein Limit von dir ist. -

    -
    -

    Was bedeuten die Exit-Codes?

    -

    - Jedes Ende hat einen eigenen Code, maschinenlesbare Ausgabe geht auf die Standardausgabe, und ein - fehlgeschlagener Lauf gibt dort nichts aus. Die Tabelle ist ein eingefrorener Vertrag - die - Bedeutung eines Codes zu ändern erfordert einen Major-Versionssprung. -

    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    CodeBedeutung
    0Alles hat funktioniert.
    1Ein unerwarteter Fehler im Tool.
    2Falscher Befehl oder falsches Flag.
    3Das Rezept ist ungültig.
    4Das Format kann nicht, was verlangt wurde.
    5Lesen oder Schreiben ist fehlgeschlagen.
    6Nicht genug Speicherplatz.
    7verify hat eine Abweichung gefunden.
    8Der Lauf ist beendet, aber nicht alles wurde erzeugt.
    130Mit Strg+C abgebrochen.
    143Durch ein Signal beendet, so sieht ein CI-Timeout aus.
    -
    -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - Ein mit Strg+C gestoppter Lauf hinterlässt trotzdem ein Manifest und nie eine halb geschriebene - Datei, sodass ein abgebrochener Job vom nächsten noch aufgeräumt werden kann. -

    -

    - Fertige Workflows für GitHub Actions und GitLab CI: So erzeugen Sie - Testdateien in einer CI-Pipeline. -

    +
    +

    Was das Werkzeug tut, nach Thema

    +
      +
    • +

      Formate

      +

      Alle Dateiformate dieses Generators, die kleinste mögliche Datei je Format und die Einstellungen, die es kennt. Alle 32 öffnen sich in ihrer Software.

      +
    • +
    • +

      Presets

      +

      Fertige Sets aus Testdateien, jedes beantwortet eine Testfrage: Upload-Limits, Dateinamen, Zeichenkodierungen, Tabellenimporte, leere Dateien und Upload-Validierung.

      +
    • +
    • +

      Beschädigte Dateien

      +

      Eine absichtlich kaputte Datei in exakt der verlangten Größe, mit einem Manifest, das sagt, dass Ihr System sie ablehnen soll. Für Upload-Validierung und Parser.

      +
    • +
    • +

      Beispieldateien

      +

      Testdateien und Beispieldateien zum Download: jedes Format mit 1 MB, beschädigte PDF-, Word- und Excel-Dateien, CSV-Tabellen und Platzhalterbilder, mit SHA-256.

      +
    • +
    • +

      Upload-Testfälle

      +

      Testfälle für einen Datei-Upload: Größenlimit, leere und beschädigte Dateien, falscher Typ, ungewöhnliche Dateinamen und Archive, jeder mit der passenden Datei.

      +
    • +
    • +

      Testdateien in CI

      +

      Testdateien in der Pipeline erzeugen statt einzuchecken: GitHub-Actions-Workflow, GitLab-Job, Exit-Codes, die den Build scheitern lassen, und die PowerShell-Falle.

      +
    • +
    • +

      Dateigröße

      +

      fsutil, dd, truncate und mkfile, jeweils auf dem passenden System gemessen - und warum eine so erzeugte Datei kein PDF und kein PNG ist, wenn ein Test eines braucht.

      +
    • +
    -
    -

    Gibt es ein Desktop-Fenster?

    -

    - Ja, dieselbe Engine mit einem Fenster davor, für das Testen, das nicht skriptbar ist. Es ist keine - abgespeckte Version: Ein Test vergleicht die beiden Oberflächen Fähigkeit für Fähigkeit, und - alles, was nur eine von beiden kann, muss deklariert und begründet werden, statt unbemerkt - auseinanderzudriften. -

    +
    +

    Immer noch nicht weiter?

    - Die Bildschirme sind ein Stapel, Presets, mehrere Stapel gleichzeitig und Info. Es zeigt, was ein - Lauf kosten würde, bevor etwas geschrieben wird, meldet den Fortschritt während des Laufs und - lässt sich mittendrin abbrechen, ohne eine halb geschriebene Datei zu hinterlassen. Eine - Rezeptdatei öffnet es noch nicht - Rezepte gibt es vorerst nur auf der Kommandozeile, und das - Fenster baut seine Stapel im Formular. + tfg <command> --help zeigt im Terminal, was ein Befehl annimmt. Jede Ablehnung nennt die Einstellung, um die es geht, den Grund und einen Wert, der funktioniert. Wenn sich etwas anders verhält, als eine Seite hier sagt, melden Sie es. Dann ist die Seite oder das Programm fehlerhaft.

    diff --git a/web/public/de/werkzeuge/index.html b/web/public/de/werkzeuge/index.html index 53f7ae2a..91057188 100644 --- a/web/public/de/werkzeuge/index.html +++ b/web/public/de/werkzeuge/index.html @@ -151,6 +151,21 @@
    +

    Dokumentation

    Ein Archiv vor dem Entpacken prüfen und Prüfsummen abgleichen

    diff --git a/web/public/docs/commands/index.html b/web/public/docs/commands/index.html new file mode 100644 index 00000000..3dc17507 --- /dev/null +++ b/web/public/docs/commands/index.html @@ -0,0 +1,571 @@ + + + + + + +Command Reference - Every tfg Command, Flag and Exit Code + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

    + +
    + +
    + +

    Commands

    +

    + Every command of tfg with every flag it takes. This page is read from the program's own + help when the page is built, so it says what the program says: tfg <command> --help + prints the same in your terminal. +

    + +
    + + + + + + + + + + + + + + + +
    CommandWhat it does
    tfg generateProduce files.
    tfg validateCheck a recipe and write nothing.
    tfg verifyCheck that a directory still matches a manifest.
    tfg cleanupRemove the files a manifest lists.
    tfg recipe fmtPrint a recipe in its settled shape, comments kept.
    tfg presetBuild a set of files from a named test question.
    tfg formatsList the formats this build supports.
    tfg damageList the ways this build can break a file on purpose.
    tfg toolSmall things to do with files you already have.
    tfg versionPrint the tool version.
    tfg licensePrint the licence and what it means for generated files.
    +
    +

    + A flag is written with two dashes, as --count 10, or with one. A flag that takes no value + is on when it is there. Every exit code is at the end of this page. +

    + +
    +

    tfg generate

    +

    Produce files.

    +
    tfg generate <recipe.yaml> [flags]   settings come from the file
    +tfg generate --format txt --size 1mb  settings come from the flags
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    FlagDefaultWhat it does
    --boundary stringthree files around a limit: one byte under it, the limit itself, one byte over
    --cleanturn off the self describing label
    --count int1how many files to produce
    --damage valuebreak the files on purpose, repeatable and applied in order: --damage zero-head, or --damage zero-head:bytes=16. This build has: append-junk, truncate, zero-head. Run "tfg damage" for what each one does
    --dry-runcount and show, write nothing at all
    --expected stringdeclared expectation: accept, reject, sanitize or unspecified
    --expected-reason stringwhy that outcome is expected, from the closed list. Run with an unknown value to see it
    --format stringformat of the files to produce, for example txt
    --id stringfilestarget id, the anchor the seeds are derived from
    --jsonwrite the manifest to standard output
    --memory valuehow much memory this run may use: auto (half of what this machine gives the program), a size such as 8gb, or off for no limit. Pictures wait for room rather than all being held at once, and a plan larger than this is refused before anything is written. When a run gets close to this amount, the program frees memory more often, which makes the run slower. A run that needs more memory than this still gets it. Under auto, a plan of up to 2.0 GB is never refused
    --name stringname template, for example invoice_{index:04}.txt
    --number-if-takenwhen --out already holds names this run would write, an earlier run's manifest above all, give every name of this run a number such as -2 rather than stopping. Nothing already there is changed. Without it such a run stops with exit code 5
    --out string.directory to write into
    --preset stringbuild the set a named test question calls for. Run "tfg preset list" to see them
    --seed intrun seed, the same seed gives the same bytes
    --send-as stringthe name to give the file to your system under, when it is one no disk stores, for example ../climbed_out.jpg. The file keeps its own name here and the manifest carries this one
    --set valueformat property, repeatable: --set width=1920 --set height=1080
    --size stringexact size of each file. Units count in 1024s, so 10mb is 10485760 bytes. Also accepts a plain byte count, or smallest for a picture with its width and height set
    --size-range stringa size drawn from a range for each file, as 1kb-8kb. The draw comes from the seed, so the same seed gives the same sizes
    +
    +
    + +
    +

    tfg validate

    +

    Check a recipe and write nothing.

    +
    tfg validate <recipe.yaml>
    +
    + + + + + + + + + + + + + + +
    FlagDefaultWhat it does
    --jsonwrite the result as JSON, with every problem separately
    --memory valuehow much memory this run may use: auto (half of what this machine gives the program), a size such as 8gb, or off for no limit. Pictures wait for room rather than all being held at once, and a plan larger than this is refused before anything is written. When a run gets close to this amount, the program frees memory more often, which makes the run slower. A run that needs more memory than this still gets it. Under auto, a plan of up to 2.0 GB is never refused
    +
    +
    + +
    +

    tfg verify

    +

    Check that a directory still matches a manifest.

    +

    Reports files that are missing, files nobody asked for, and files whose content has changed. The directory is always a local one.

    +
    tfg verify <manifest.json> [--against <dir>]
    +
    + + + + + + + + + + + + + + + + + + + +
    FlagDefaultWhat it does
    --against stringdirectory to check. Defaults to the directory holding the manifest
    --jsonwrite the report to stdout as JSON
    --memory valuehow much memory checking may use: auto (half of what this machine gives the program), a size such as 8gb, or off for no limit. A manifest listing more files than that can check is refused before any file is looked at. When checking gets close to this amount, the program frees memory more often, which makes it slower
    +
    +
    + +
    +

    tfg cleanup

    +

    Remove the files a manifest lists.

    +

    Removes what the manifest lists and nothing else. Without --yes it deletes nothing and prints what it would remove. A file whose content has changed since it was written is left alone and reported, because it may not be ours.

    +
    tfg cleanup <manifest.json> [--yes]
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    FlagDefaultWhat it does
    --against stringdirectory to clean. Defaults to the directory holding the manifest
    --forceremove files whose content has changed since they were written
    --jsonwrite the report as JSON instead of prose
    --memory valuehow much memory checking may use: auto (half of what this machine gives the program), a size such as 8gb, or off for no limit. A manifest listing more files than that can check is refused before any file is looked at. When checking gets close to this amount, the program frees memory more often, which makes it slower
    --with-manifestremove the manifest and the instructions beside it as well, once every file it lists is gone
    --yesactually remove the files. Without this nothing is deleted and the list is printed
    +
    +
    + +
    +

    tfg recipe fmt

    +

    Print a recipe in its settled shape, comments kept.

    +

    This settles the layout of a file. It does not check that the recipe makes sense - a file with a key nobody recognises or a format that does not exist still has a settled shape, and this will print it. Run "tfg validate" for that, and run both if you are checking recipes before a commit.

    +
    tfg recipe fmt <recipe.yaml>
    +
    + + + + + + + + + + + + + + +
    FlagDefaultWhat it does
    --checkprint nothing and end with code 3 when the layout is not settled. It says nothing about whether the recipe is valid - use tfg validate for that
    -wwrite the result back to the file instead of printing it
    +
    +
    + +
    +

    tfg preset

    +

    Build a set of files from a named test question.

    +
    tfg preset list                       what this build offers
    +tfg preset show <id>                  what it takes and what it would produce
    +tfg preset eject <id> -o my.yaml      the recipe it stands for, to edit
    +

    A preset is a recipe with a name. Ejecting one gives back an ordinary recipe file, so nothing here is a closed box.

    +

    Run "tfg generate --preset <id>" to produce the files.

    +
    + +
    +

    tfg formats

    +

    List the formats this build supports.

    +

    Says three things a request depends on and that nobody can guess: how faithful the file will be, whether it repeats to the byte, and how small it can go.

    +
    tfg formats
    +tfg formats --json
    +
    + + + + + + + + + +
    FlagDefaultWhat it does
    --jsonwrite the list as JSON to standard output
    +
    +
    + +
    +

    tfg damage

    +

    List the ways this build can break a file on purpose.

    +

    A damaged file comes out exactly the size you asked for. Where the damage breaks the rules of the format, the manifest expects the file to be rejected. Where readers differ - a text cut short is still text - it says the outcome depends on your system, and why. Use them with "tfg generate --damage <id>" or with the damage key of a recipe.

    +
    tfg damage
    +tfg damage --json
    +tfg damage <id>
    +
    + + + + + + + + + +
    FlagDefaultWhat it does
    --jsonwrite the list as JSON to standard output
    +
    +
    + +
    +

    tfg tool

    +

    Small things to do with files you already have.

    +
    tfg tool list                    the tools this build has
    +tfg tool show <id>               what one tool works on and takes
    +tfg tool <id> <path> [flags]     run it
    +

    Every tool is also on the Tools tab of the window, with the same settings.

    +
    + +
    +

    tfg version

    +

    Print the tool version.

    +
    + +
    +

    tfg license

    +

    Print the licence and what it means for generated files.

    +
    + +
    +

    Exit codes

    +

    + Every ending has a code of its own, so a script or a pipeline can tell them apart. Output meant for + a program goes to standard output, and a run that fails prints nothing there. The meaning of a code + never changes within a major version. +

    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    CodeMeaning
    0Everything worked.
    1An unexpected error inside the tool.
    2Wrong command or flag.
    3The recipe is not valid.
    4The format cannot do what was asked.
    5A read or a write failed.
    6Not enough disk space.
    7verify found a mismatch.
    8The run finished but not everything was produced.
    130Interrupted with Ctrl+C.
    143Stopped by a signal, which is what a CI timeout looks like.
    +
    +

    + A run stopped with Ctrl+C still leaves a manifest and never a half written file, so the next run + can clean up after it. In PowerShell, end a script with exit $LASTEXITCODE, because a + .ps1 file does not pass the code of a program on by itself. More in + Test files in CI. +

    +
    + +
    + + + + diff --git a/web/public/docs/desktop-app/index.html b/web/public/docs/desktop-app/index.html new file mode 100644 index 00000000..1c2fd865 --- /dev/null +++ b/web/public/docs/desktop-app/index.html @@ -0,0 +1,262 @@ + + + + + + +Desktop App - Generate Test Files Without the Command Line + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +

    Desktop app

    +

    + tfg-gui is the same program with a window on it, for the testing that is not scripted. + It makes the same files from the same settings as the command line, and a test compares the two + screen by screen, so nothing one of them can do quietly goes missing from the other. +

    + +
    +

    Before anything is written

    +

    + Every screen shows what a run would make before you start it: how many files, how many bytes, which + formats and where they go. Preview lists the files without writing any. A run shows its progress + and can be cancelled part way without leaving a half written file behind. +

    +
    + +
    +

    Single batch

    +

    + Files of one format: choose the format, how the size is given, the size and how many files. The + settings of the format open under the form, and a box beside every field says what it does. A value + the format cannot take is marked under its field, with the value that would work. +

    +
    + The Single batch screen: format, size, how many files, damage, batch name and the output folder +
    +
    + +
    +

    Presets

    +

    + A ready set that answers one question about the system you test, such as whether a size limit is + enforced exactly where it is declared. The screen says what each preset typically finds, takes its + settings, and shows the cost of the set before it is made. + Presets describes every one. +

    +
    + The Presets screen with a preset chosen, what it typically finds, its settings and the output folder +
    +
    + +
    +

    Several batches

    +

    + Batches of different formats and sizes made together in one run, with one manifest. A batch can be + duplicated and changed, can carry notes for the manifest, and the whole run can start from a preset, + whose files come first. +

    +
    + The Several batches screen with one batch, the choice to build on a preset, and the output settings +
    +
    + +
    +

    Tools

    +

    + The tools for files you already have, with the same settings as tfg tool: a checksum + compared with the one you were given, checksums for a whole folder, and whether an archive is safe to + unpack. A file or a folder dropped on the screen goes into the box of the chosen tool. + Tools says what each one finds. +

    +
    + The Tools screen with a checksum worked out and matching the one that was expected +
    +
    + +
    +

    Preferences and About

    +

    + Preferences sets the language of the window, how much memory a run may take, and shows what the + window keeps between runs and where. Forget clears what it keeps. Only the window changes language. + The files, recipes, manifests and the command line stay in English. About shows the version, how to + use the window in three steps, and the licence. +

    +
    + +
    +

    The output folder

    +

    + A folder dropped on the window becomes the output folder. A run into a folder that holds an earlier + run is added beside it: every name of the run, its manifest too, gets a number, as + files-2_0001.pdf and manifest-2.json, and nothing already there changes. The + switch for this, Add beside earlier runs, stays on unless you turn it off. With it off, such a run is + refused, the same as on the command line without --number-if-taken. +

    +
    + +
    +

    What it does not do yet

    +

    + The window does not open a recipe file. Recipes are a command line thing for now, and the window + builds its batches in the form. If the window does not open at all, see + when the window does not open. +

    +
    + +
    + + + + diff --git a/web/public/docs/format-settings/index.html b/web/public/docs/format-settings/index.html new file mode 100644 index 00000000..b8110575 --- /dev/null +++ b/web/public/docs/format-settings/index.html @@ -0,0 +1,1605 @@ + + + + + + +Format Settings - Every Option of Every Test File Format + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +

    Format settings

    +

    + Every setting each format takes, with the values it accepts, its default and what it changes in the + file. The list is read from the program when this page is built, in the program's own words: + tfg formats <id> prints the same for one format. +

    + +
    +

    How to give a setting

    +

    On the command line, --set takes one setting and repeats. In a recipe, the settings go under properties:

    +
    tfg generate --format pdf --size 1mb --set pages=20 --set page_size=letter --out ./pdf
    +
    targets:
    +  - id: report
    +    format: pdf
    +    size: 1mb
    +    properties:
    +      pages: 20
    +      page_size: letter
    +

    + A setting left out takes its default. A value outside what the setting accepts is refused before + anything is written, with the values that would work. Some settings also limit the smallest size a + file can be, and a size below it is refused with the size that would work. The list of formats + themselves, with the smallest file of each, is on Formats. +

    +

    + avif bmp csv docx eml geojson gif html ico jpg json jxl log md mp4 otlp pdf png pptx rtf svg targz tiff txt wav webm webp xlsx xml zip +

    +
    + +
    +

    avif AV1 Image File Format

    +
    + + + + + + + + + + + + + + + + + + + + + + +
    SettingAcceptsDefaultWhat it does
    width1 - 16384 pixelsHow wide the picture is. Left out, a size is chosen that fits the bytes you asked for.
    height1 - 16384 pixelsHow tall the picture is. Left out, a size is chosen that fits the bytes you asked for.
    quality1 - 10060How much detail the picture keeps. Higher looks better and takes more of the file, leaving less room for padding.
    +
    +
    + +
    +

    bmp Windows Bitmap

    +
    + + + + + + + + + + + + + + + + +
    SettingAcceptsDefaultWhat it does
    width1 - 20000 pixelsHow wide the picture is. Left out, the picture is sized to fill the bytes you asked for.
    height1 - 20000 pixelsHow tall the picture is. Left out, the picture is sized to fill the bytes you asked for.
    +
    +
    + +
    +

    csv Comma-Separated Values

    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    SettingAcceptsDefaultWhat it does
    delimitercomma, pipe, semicolon, tabcommaWhat separates the fields. Choose semicolon for the shape a European spreadsheet exports.
    line_endingcrlf, lflfHow each row ends. Choose crlf for the shape RFC 4180 asks for and Excel writes.
    headertrue or falsetrueWhether the first row names the columns. Turn it off for a table dumped straight out of a database.
    quote_styleall, minimal, noneminimalWhich fields carry quotes. With none the description stops carrying separators as well, because an unquoted field cannot hold one.
    columns2 - 32768 columns6How many columns each row has. Above 16384 a spreadsheet may show only the first 16384 and drop the rest without a word.
    +
    +
    + +
    +

    docx Word (Office Open XML)

    +
    + + + + + + + + + + +
    SettingAcceptsDefaultWhat it does
    paragraphs1 - 50000 paragraphs1How many paragraphs of text the document holds. The rest of the size you asked for is carried by a part of the package that is not shown.
    +
    +
    + +
    +

    eml Email message

    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    SettingAcceptsDefaultWhat it does
    bodyalternative, html, plainplainWhich text the message carries. With plain text and HTML the same words go in both, and a mail program shows one of them.
    layoutnewsletter, simplesimpleHow the text is laid out. simple is the text alone. newsletter wraps it the way a mailing list does - a title, a Read more button and a footer with an unsubscribe link, in a table 600 pixels wide styled both by a style sheet and by style attributes, and the plain text writes out the addresses the HTML puts behind its links. It adds List-Id, List-Unsubscribe and List-Unsubscribe-Post, by which mail systems tell bulk mail apart, and the manifest gives the unsubscribe address as unsubscribe_url. The message has no DKIM signature, so a mail program that follows RFC 8058 offers no one-click unsubscribe. Messages inside stay simple.
    text_encoding7bit, 8bit, base64, quoted-printable7bitHow the text is written. 7bit keeps it to plain ASCII. quoted-printable, 8bit and base64 add a line in Polish, and in Japanese when the charset is utf-8, because that is what they are for. quoted-printable spells those letters as =C5=BC, 8bit writes them as they are, and base64 writes the whole text in base64. To reach every size base64 ends the text with empty lines, and with crlf an odd size gives the Message-ID one more digit.
    charsetiso-8859-2, utf-8, windows-1250utf-8The character set of the text when the text encoding is not 7bit. iso-8859-2 and windows-1250 hold Polish and no Japanese, and they write ą, ś and ź as different bytes, so a program that takes one for the other shows the wrong letters. MimeKit with no code page provider registered tries UTF-8 and then Latin-1, which shows the Polish letters of both wrong, and reads them right once one is. Go's standard library converts no character set at all. With 7bit the text is plain ASCII and says us-ascii, whatever this is set to.
    headersascii, encoded, utf8asciiWhether the subject, the names of the sender and the recipient and the names of attached files carry letters outside ASCII, and how. encoded writes them the way RFC 2047 and RFC 2231 say. utf8 writes them as they are (RFC 6532), and Python's email package reads that and reports a defect in the From and To lines.
    recipients1 - 1000001How many addresses the To line carries, each on a line of its own. mailparser refuses a header of more than 1 MiB, which about 33 800 addresses reach with crlf and 34 900 with lf, and Python 3.14's email package takes minutes over tens of thousands of them.
    line_endingscrlf, lfcrlfHow every line of the file ends. The standard is crlf. Python, MimeKit, mailparser and Go's standard library all read lf too, so the difference shows in programs that split the lines themselves.
    attachments0 - 100000How many files the message carries. When the files are not all alike, describe each kind on its own instead - with Add files inside on Several batches, or contains in a recipe. mailparser refuses a message of more than 1000 MIME entities, and the manifest gives this one's count as mime_entities.
    attachment_formatthe id of a format, such as png or csvtxtThe format of the attached files. eml attaches a message as it is, the way mail is forwarded, with no base64 around it.
    attachment_sizea size such as 2mb8kbHow big each attached file is. The message grows by about a third more, because attached files travel in base64.
    filename_styleboth, content-type, none, rfc2047, rfc2231rfc2231How the names of attached files and pictures are written. rfc2231 is the standard way. rfc2047 is the encoded form RFC 2047 forbids inside a name, and many readers decode it anyway. both writes the two, and content-type puts the name only where old mail programs looked for it. none writes no name at all, and a program that needs one has to make one up - Thunderbird 157 calls them Part 1.2, Part 1.3 and so on. Go's standard library reads no name from content-type and the encoded text itself from rfc2047. Unless the headers are encoded, a name is written as it is and only where it goes changes, so rfc2047 and both write the same bytes.
    message_depth1 - 20001How many messages deep the message goes. 1 is a message alone. 2 carries a forwarded message as an attachment, and each step adds one more inside the last, the smallest message each can be. Python 3.14's email package runs out of recursion at around 490, and MimeKit stops taking them apart past 513 without a word. Thunderbird 157 shows up to 32 in full. Past that the 32nd message inside shows only its headers and nothing under it appears, without a word.
    inline0 - 100000How many pictures the text shows. With html and alternative each one sits beside the HTML and the HTML points at it through cid:. With plain there is no HTML to point from, so they travel after the text as pictures to show inline. mailparser lists them among the attachments, and so does Python's email package when the HTML is alone. MimeKit never does.
    inline_formatthe id of a picture format, such as png or jpgpngThe format of the pictures. Any format whose files are pictures, such as png, jpg or gif.
    inline_sizea size such as 2mb8kbHow big each picture is. Like an attached file it travels in base64, about a third larger.
    +
    +
    + +
    +

    geojson GeoJSON

    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    SettingAcceptsDefaultWhat it does
    geometrygeometrycollection, linestring, mixed, multilinestring, multipoint, multipolygon, point, polygonmixedWhich kind of geometry each feature carries. With mixed the seven kinds take turns, so a file of seven features or more holds every one of them.
    formattingindented, minified, record-per-linerecord-per-lineHow the document is laid out. Every reader accepts all three - minified puts the whole file on one line and ends without a newline, and indented puts every number on its own line, which makes the same features several times larger.
    precision0 - 15 decimal places6How many decimal places every coordinate is written with. Six is about ten centimetres on the ground, the figure RFC 7946 gives.
    altitudetrue or falsefalseWhether every position carries a third number, the height in metres from -400 to 8848. A program that reads two numbers a position has to ignore it or refuse the file.
    vertices3 - 1000000 points8How many points every line, outline and MultiPoint has. A feature larger than 1 MiB is followed by spaces that fill the last bytes, and at precision 3 or less fewer points fit, because each needs its own step of longitude.
    holes0 - 100000 holes0How many holes every polygon has inside its outline. Each hole has four points and runs the other way round to its outline, as RFC 7946 asks. Holes need 6 or more vertices, fewer of them fit at precision 3 or less, and points and lines do not change.
    windingreversed, rfc7946rfc7946Which way polygon outlines run - rfc7946 is counter-clockwise and reversed is clockwise, and holes always run the other way. RFC 7946 tells readers to accept both, and they disagree about which side of the outline is inside. Points and lines do not change.
    antimeridiantrue or falsefalseWhether every line and outline crosses the 180th meridian without being cut in two. RFC 7946 asks for such shapes to be cut, and readers differ - read as flat coordinates, a crossing outline crosses itself and runs the other way round. A single point cannot cross and is placed beside it.
    unlocatedall, none, somenoneHow many features have no place - RFC 7946 writes their geometry as null. some takes the place of every fifth feature, from the fifth on, and all takes it from every one, so the settings that shape a geometry change nothing.
    idsmixed, none, number, stringnumberWhich type every feature id has. RFC 7946 allows a number or a string, mixed gives odd features a number and even ones a string such as f2, and none leaves the id out. Readers that turn the id into a key may keep only one of the two types.
    bboxtrue or falsefalseWhether the collection and every feature with a place carry a bbox, the box their coordinates lie in. The collection's bbox follows its features, because its extent is known only after the last one, and a box across the antimeridian has a west edge greater than its east edge, as RFC 7946 asks.
    +
    +
    + +
    +

    gif Graphics Interchange Format

    +
    + + + + + + + + + + + + + + + + + + + + + + +
    SettingAcceptsDefaultWhat it does
    width1 - 20000 pixelsHow wide the picture is. Left out, a size is chosen that fits the bytes you asked for.
    height1 - 20000 pixelsHow tall the picture is. Left out, a size is chosen that fits the bytes you asked for.
    frames1 - 603How many frames the animation has. Set it to 1 for a still picture.
    +
    +
    + +
    +

    html HyperText Markup Language

    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    SettingAcceptsDefaultWhat it does
    structuredocument, fragmentdocumentWhether the file is a whole page or only the blocks that would sit inside one. A fragment has no doctype, no html element and no body, which is what a content field or the body of an email really holds. It is far smaller, so the smallest fragment sits well below the smallest page.
    nesting0 - 1000000How many div elements the content sits inside, each one inside the last. 0 puts it straight in the body, and the label stays outside so the page still says what it is. Chromium keeps 511 levels and moves the deeper ones out, and the Nu HTML Checker calls a page that deep an error. lxml drops the content of a page nested about 250 deep and keeps only the label, and jsdom, parse5 and DOMPurify can run out of stack writing out a page from about 2 000 deep.
    charactersascii, internationalasciiWhether the page carries text outside ASCII. international adds paragraphs in Polish, Russian, Japanese and Arabic, the Arabic right to left, with emoji, a letter written as two code points and named and numbered entities. A program without a Japanese or Arabic font shows boxes in their place.
    elementsbasic, everybasicWhich elements the page uses. basic is headings, paragraphs, lists, tables and quotes. every adds a block that uses every element of the HTML standard at least once, all 22 kinds of input and small pictures and a sound inside the page, with no script and nothing fetched from a network. A fragment has no head, so it leaves out the eight elements that only a whole page holds.
    links0 - 10000000How many links the page carries, in a list above the pictures and the blocks. They go through 18 kinds in turn and then repeat - a link to the list itself, relative, to the folder above, from the root, a query alone, absolute with a query and a fragment, http, without a scheme, percent encoded, an international domain, a port, mailto:, tel:, ftp:, a download, a new window, nofollow and data: - and the text of each says which it is. Every address is on a domain kept for examples. DOMPurify with its defaults takes out the data: address and the target that opens a new window, and it ran out of 8 GB of memory over a million links, which lxml read in 3 seconds. The catalogue of every element has six links of its own, which this does not count.
    bomtrue or falsefalseWhether the file opens with a byte order mark. A reader that has to guess the encoding needs one, and a reader that does not expect it shows it as stray characters at the start of the file.
    formattingindented, lines, minifiedlinesHow the page is laid out. minified puts the whole file on one line and ends without a newline. indented puts two spaces in front of a line for every element it sits in, and leaves the text of pre as it is. All three show the same. A program reading line by line gets a minified page as one line - Go's bufio.Scanner refuses a line past 64 KB unless given a larger buffer - and text read by joining what the elements hold runs the last word of one block into the first word of the next. Indented with nesting puts more spaces in front of every line with each level, so nesting 1000 makes a page of at least 1.9 MB.
    stylesembedded, inline, nonenoneWhether the page carries CSS, and where. embedded puts the rules in a style element, in the head of a page and at the very start of a fragment. inline puts the same rules in a style attribute on every heading, paragraph, list, table and quote the page is filled with, and the page looks the same. DOMPurify with its defaults drops the style element without listing it as removed and keeps the attributes. lxml's text_content and BeautifulSoup on html5lib count the rules as text of the page. The catalogue of every element takes the embedded rules and no attributes.
    inline0 - 100000How many pictures the page shows, each one a real file of its format written into the page as a data: URL, so opening the page fetches nothing. They sit above the blocks, each in a paragraph of its own, and each says which it is in its alt text.
    inline_formatthe id of a picture format, such as png or jpgpngThe format of the pictures. Any format whose files are pictures, such as png, jpg or gif. Chromium shows every one of them but tiff.
    inline_sizea size such as 2mb8kbHow big each picture is. Inside the page it is base64 on one line, about a third larger. lxml, and BeautifulSoup on top of it, leave out a picture past about 7.1 MB unless told to read huge trees. On Linux lxml took over 20 seconds over such a page, and with a 15 MB picture it lost the rest of the page as well.
    +
    +
    + +
    +

    ico Windows Icon

    +
    + + + + + + + + + + + + + + + + + + + + + + +
    SettingAcceptsDefaultWhat it does
    width1 - 256 pixelsHow wide the icon is. Left out, the largest standard icon size that fits is used.
    height1 - 256 pixelsHow tall the icon is. Left out, the largest standard icon size that fits is used.
    embedbmp, pngbmpWhat sits inside the icon. A bitmap is read by every version of Windows. A PNG makes the file much smaller and needs Windows Vista or newer.
    +
    +
    + +
    +

    jpg JPEG

    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    SettingAcceptsDefaultWhat it does
    width1 - 20000 pixelsHow wide the picture is. Left out, a size is chosen that fits the bytes you asked for.
    height1 - 20000 pixelsHow tall the picture is. Left out, a size is chosen that fits the bytes you asked for.
    quality1 - 10090How much detail survives compression, from 1 to 100. JPEG throws detail away by design, so a low number gives a visibly softer picture. It changes how large the picture encodes to, not the size of the file you asked for.
    contentplaceholder, testtestWhat the picture shows. A test pattern is for checking how a file is read. A placeholder is a flat colour with words in the middle, for laying out a page before the real pictures exist.
    textone line of up to 100 characters{width} × {height}The words in the middle of a placeholder. {width} and {height} become the size of the picture, {index} the number of the file and {index:04} the same number with four digits.
    backgrounda colour such as cccccc or cccccccccThe colour of a placeholder, such as cccccc or ccc. In a recipe write it without # or in quotes, because # starts a comment there.
    foregrounda colour such as cccccc or ccc555555The colour of the words and the guides on a placeholder, written the same way as background.
    guidestrue or falsefalseDraws a frame along the edges of a placeholder, both diagonals and a circle touching its shorter sides, so you can see where a page crops or stretches the picture.
    +
    +
    + +
    +

    json JavaScript Object Notation

    +
    + + + + + + + + + + +
    SettingAcceptsDefaultWhat it does
    formattingindented, minified, record-per-linerecord-per-lineHow the document is laid out. Every reader accepts all three, so this changes what meets everything around the parser rather than the parser itself - minified puts the whole file on one line and ends without a newline, and indented makes the same records several times larger.
    +
    +
    + +
    +

    jxl JPEG XL

    +
    + + + + + + + + + + + + + + + + + + + + + + +
    SettingAcceptsDefaultWhat it does
    width1 - 16384 pixelsHow wide the picture is. Left out, a size is chosen that fits the bytes you asked for.
    height1 - 16384 pixelsHow tall the picture is. Left out, a size is chosen that fits the bytes you asked for.
    quality1 - 10090How much detail the picture keeps. Higher looks better and takes more of the file, leaving less room for padding.
    +
    +
    + +
    +

    log Server and application log

    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    SettingAcceptsDefaultWhat it does
    entry_formatapache-combined, apache-common, json-lines, nginx, plain, syslogapache-combinedWhich kind of log to write. Web server shapes carry a request and a status, the others carry a level and a message.
    timestampsadvancing, fixedadvancingWhether each entry happens later than the one before it. Fixed puts every entry at the same instant, which is what this format did before it could advance.
    rate1 - 1000000 entries per second1How fast the entries arrive. Only means anything while timestamps advance.
    methodsget, mixed, readgetWhich request methods appear: GET only, GET and HEAD, or mixed, which adds POST, PUT, PATCH and DELETE to those two.
    status_mixclient-errors, realistic, server-errors, successrealisticWhich response codes appear. Realistic is mostly success with a tail of errors.
    level_mixdebug, errors, quiet, realisticrealisticWhich severities appear. Only the plain and JSON Lines shapes carry one, and asking for it beside another shape is refused.
    ip_versionmixed, v4, v6v4Which kind of client address appears. Choose v6 to find out whether a reader handles it.
    line_endingcrlf, lflfHow each line ends. Choose crlf for a log written by a Windows service.
    +
    +
    + +
    +

    md Markdown

    +
    + + + + + + + + + + + + + + + + +
    SettingAcceptsDefaultWhat it does
    encodingutf-16be, utf-16le, utf-8utf-8Which encoding the characters are written in. UTF-16 stores two bytes per character, so a file in it always has an even number of bytes and an odd size is refused.
    bomtrue or falsefalseWhether the file opens with a byte order mark. A reader that has to guess the encoding needs one, and a reader that does not expect it shows it as stray characters at the start of the file.
    +
    +
    + +
    +

    mp4 MP4 video

    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    SettingAcceptsDefaultWhat it does
    width1 - 16384 pixelsHow wide the picture is. Left out, a size is chosen that fits the bytes you asked for.
    height1 - 16384 pixelsHow tall the picture is. Left out, a size is chosen that fits the bytes you asked for.
    durationa length of time such as 10s10sHow long the film plays. It has to end on a frame, so at 30 frames a second it goes in steps of 100ms.
    change_intervala length of time such as 10s1sHow often the picture changes: the clock in it moves on and the square takes a step. Each change costs a whole picture in bytes. An interval as long as the film or longer keeps one picture throughout.
    frame_rate1, 5, 10, 12, 15, 24, 25, 30, 48, 50, 6030How many frames the film shows each second.
    keyframe_intervala length of time such as 10s1mHow far apart the frames are that a player can start from. Shorter makes skipping through a long film faster and the file bigger, because each of them carries the whole picture twice.
    quality1 - 10060How much detail the picture keeps. Higher looks better and takes more of the file, leaving less room for padding.
    +
    +
    + +
    +

    otlp OpenTelemetry Protocol JSON

    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    SettingAcceptsDefaultWhat it does
    signallogs, metrics, tracestracesWhich kind of telemetry the file holds. traces writes spans, logs writes log records and metrics writes the measurements of a service, collected every interval. A file holds one kind, as the OTLP file format asks.
    formattingindented, minified, record-per-linerecord-per-lineHow the file is laid out. Record per line puts one batch on each line, which is what the OTLP file exporter writes and the file receiver of the OpenTelemetry Collector reads, and the file name ends in .jsonl. Minified and indented make the whole file one request, the body to post to an OTLP endpoint, and the file name ends in .json. Posted as a body, a file of several lines loses every line after the first in the Collector, and its file receiver reads nothing from an indented file.
    bomtrue or falsefalseWhether the file opens with a byte order mark. A reader that has to guess the encoding needs one, and a reader that does not expect it shows it as stray characters at the start of the file.
    batch1 - 1000512How many spans or log records each line holds. 512 is the batch an OpenTelemetry SDK sends by default. Only the formatting record per line has batches. Beside other formatting, or beside the signal metrics, where a line holds one collection, a batch is refused.
    starta moment in UTC such as 2026-08-01T12:00:00Z2026-08-01T12:00:00ZThe moment the first span or log record is dated, and the moment a service writing metrics started. The later ones follow it at the rate or every interval. Change it when the system that receives the file refuses or hides data that is too old.
    rate1 - 1000000 entries per second1How many traces or log records begin each second. Metrics are collected every interval instead, and beside signal metrics a rate is refused.
    depth1 - 1003How many spans each trace has, each one the child of the one before it. 1 leaves every span without a parent. It shapes spans, and beside signal logs or metrics it is refused.
    status_mixclient-errors, realistic, server-errors, successrealisticWhich response codes the requests end with. A code of 500 or above marks its span as an error, as the HTTP conventions of OpenTelemetry ask, and every other code leaves the status unset. It shapes spans, and beside signal logs or metrics it is refused.
    level_mixdebug, errors, quiet, realisticrealisticWhich severities the log records carry. Realistic is mostly INFO with some of the others. It shapes log records, and beside signal traces or metrics it is refused.
    trace_contexttrue or falsetrueWhether every log record names the trace and the span it was written in. The file holds no spans, so those ids match nothing in it. It shapes log records, and beside signal traces or metrics it is refused.
    metric_kindexponential-histogram, gauge, histogram, mixed, sum, summarymixedWhich metrics the file holds. gauge writes jvm.cpu.recent_utilization and shop.orders.pending, sum writes jvm.cpu.time, jvm.class.loaded and jvm.memory.used, histogram writes http.server.request.duration in the buckets the OpenTelemetry conventions name, exponential histogram writes jvm.gc.duration in buckets that double every eight, and summary writes http.server.requests as three percentiles, the way Micrometer writes a timer. mixed writes all of them. gauge and sum each hold whole numbers and fractions.
    temporalitycumulative, deltacumulativeWhether a sum or a histogram counts everything since the service started or only what came since the collection before. cumulative is what an SDK sends by default. delta leaves jvm.memory.used cumulative, as the delta setting of an SDK does. Beside the metric kind gauge or summary it is refused.
    exemplarstrue or falsefalseWhether the durations of requests name the trace and the span a measurement was taken in, one for each bucket a collection measured in. The file holds no spans, so those ids match nothing in it. Only http.server.request.duration has them, and beside a metric kind without it they are refused.
    interval1 - 86400 seconds60How long a service waits between two collections of its metrics. 60 is what an SDK uses by default. Every point of a collection is dated at the same moment, and with the formatting record per line a line holds one collection.
    id_encodingbase64, hex, upper-hexhexHow trace and span ids are written. hex is what the OTLP specification asks for. Upper-case hex writes the same digits in capitals, which the specification allows, and the OpenTelemetry Collector writes them back in lower case. base64 writes them the way the JSON mapping of protobuf writes bytes, which the specification forbids - the file receiver of the Collector drops every batch that holds an id without a word and its HTTP receiver answers 400. A reader built on the protobuf library reads base64 ids right and hex ids as something else.
    enum_encodingname, numbernumberHow the kind of a span, the code of its status, the severity of a log record and the temporality of a sum or a histogram are written. number is what the OTLP specification asks for. name writes names such as SPAN_KIND_SERVER, which the specification forbids. The OpenTelemetry Collector reads them anyway and writes numbers back, and the Rust crate opentelemetry-proto refuses a span written that way.
    key_casecamel, snakecamelHow the keys of the file are written. camelCase is what the OTLP specification asks for, such as traceId. snake_case writes the names the .proto files give the fields, such as trace_id, which the specification calls not valid. The OpenTelemetry Collector reads them and writes camelCase back, and the Rust crate opentelemetry-proto refuses the file.
    large_numbersnumber, texttextHow times and the other numbers of 64 bits are written. text is what the OTLP specification asks a writer for, such as "1785585600000000000". number writes them as JSON numbers, which a reader is told to take as well, and the OpenTelemetry Collector does. A reader that holds every JSON number as a double, as JavaScript does, gets every time to the nearest 256 nanoseconds.
    time_orderin-order, out-of-orderin-orderWhether every trace, log record or collection is dated later than the one before it. Out of order swaps the times of every two neighbours, so every second one is dated before the one in front of it. The specification of the OTLP file promises no order, and the OpenTelemetry Collector reads the file and writes it back unchanged. What the system storing the data does with what comes late is the question this file asks.
    end_before_starttrue or falsefalseWhether every span is dated with its end before its start, the two times changed places. The OpenTelemetry Collector reads such a span and writes it back unchanged. It shapes spans, and beside signal logs or metrics it is refused.
    empty_envelopetrue or falsefalseWhether the file opens with a line holding a batch with nothing in it, which the OTLP specification asks senders not to write. The file receiver of the OpenTelemetry Collector reads the line and writes nothing for it. Only the formatting record per line has a line to spare, and beside other formatting it is refused.
    bodyany-value, texttextWhat the body of a log record holds. Text is a sentence. Every kind of value gives the seven kinds of value OTLP has in turn - text, a boolean, the whole number 2^53 + 1, a fraction, a list, a map and bytes - and the OpenTelemetry Collector reads them and writes them back unchanged. With large numbers written as JSON numbers, a reader that holds numbers as doubles reads that whole number one less. It shapes log records, and beside signal traces or metrics it is refused.
    non_finitetrue or falsefalseWhether jvm.cpu.recent_utilization reports values that are not numbers: NaN in the second of every four collections, and Infinity and -Infinity in turn in the fourth, written as text the way the JSON mapping of protobuf writes them. The OpenTelemetry Collector reads them and writes them back unchanged. Beside a metric kind without that gauge it is refused.
    +
    +
    + +
    +

    pdf Portable Document Format

    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    SettingAcceptsDefaultWhat it does
    pages1 - 50001How many pages the document has.
    page_sizea3, a4, a5, legal, letter, mixeda4The paper size every page uses. Mixed goes through a4, letter, legal, a3 and a5 in turn, one a page, and needs at least two pages.
    orientationlandscape, mixed, portraitportraitWhether pages stand upright or lie wide. Mixed alternates the two, starting upright, and needs at least two pages.
    rotate0, 90, 180, 2700Asks the reader to turn every page clockwise by this many degrees when it shows it. The page itself stays upright, so a reader that ignores the request shows it unturned.
    pdf_version1.4, 1.71.7The version written at the start of the file. Nothing else changes, because the document uses nothing newer than 1.4.
    titleany textThe title a reader shows in its title bar and in the document properties. Left empty, the title is the self describing label, or the name of this tool without one.
    authorany textThe author in the document properties. Left empty, the document names none.
    subjectany textThe subject in the document properties. Left empty, the document has none.
    keywordsany textThe keywords in the document properties, as one line of text. Left empty, the document has none.
    creatorany textThe program the document says it was written in, such as Microsoft Word. Left empty, the document names none.
    producerany textTesting Files GeneratorThe program the document says turned it into a PDF.
    createda date such as 2024-02-29 or 2024-02-29T13:45:00+02:00, or none2020-01-01T00:00:00ZWhen the document says it was created. A time written without a zone is kept without one, and none leaves the date out.
    modifieda date such as 2024-02-29 or 2024-02-29T13:45:00+02:00, or noneWhen the document says it was last changed, written the same way as created. Left empty, the document has no such date.
    +
    +
    + +
    +

    png Portable Network Graphics

    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    SettingAcceptsDefaultWhat it does
    width1 - 20000 pixelsHow wide the picture is. Left out, a size is chosen that fits the bytes you asked for.
    height1 - 20000 pixelsHow tall the picture is. Left out, a size is chosen that fits the bytes you asked for.
    contentplaceholder, testtestWhat the picture shows. A test pattern is for checking how a file is read. A placeholder is a flat colour with words in the middle, for laying out a page before the real pictures exist.
    textone line of up to 100 characters{width} × {height}The words in the middle of a placeholder. {width} and {height} become the size of the picture, {index} the number of the file and {index:04} the same number with four digits.
    backgrounda colour such as cccccc or cccccccccThe colour of a placeholder, such as cccccc or ccc. In a recipe write it without # or in quotes, because # starts a comment there.
    foregrounda colour such as cccccc or ccc555555The colour of the words and the guides on a placeholder, written the same way as background.
    guidestrue or falsefalseDraws a frame along the edges of a placeholder, both diagonals and a circle touching its shorter sides, so you can see where a page crops or stretches the picture.
    +
    +
    + +
    +

    pptx PowerPoint (Office Open XML)

    +
    + + + + + + + + + + +
    SettingAcceptsDefaultWhat it does
    slides1 - 500 slides1How many slides the presentation holds. The rest of the size you asked for is carried by a part of the package that is not shown.
    +
    +
    + +
    +

    rtf Rich Text Format

    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    SettingAcceptsDefaultWhat it does
    charactersascii, internationalasciiWhether the document carries text outside ASCII. international adds paragraphs in Polish, Russian, Japanese and Arabic, the Arabic right to left, and one with emoji, a letter written as two code points, the three characters RTF escapes and the ones it names, such as the dashes and the quotes. A program without a Japanese or Arabic font shows boxes in their place.
    text_encodingboth, codepage, literal, unicodeunicodeHow the letters outside ASCII are written, which changes nothing while the characters are ascii. unicode writes each one as a number with a question mark after it for a reader that does not know numbers. Unicode and code page also puts the letter in the code page of its font after the number, two bytes for Japanese, the way Word writes it. Code page writes only the code page bytes, and the emoji still as numbers, since no code page holds them. literal writes the question mark as a plain character. LibreOffice, Tika and the RichEdit control of Windows read all four. pandoc shows code page text in the wrong letters. pandoc before 3.13 also drops the character after every letter written literal, and pandoc 3.1 and 3.7 drop the emoji in all four. striprtf returns an emoji as two halves, which Python refuses to write as UTF-8.
    elementsbasic, everybasicWhich parts the document uses. basic is headings, paragraphs with bold and italic words, lists, tables and indented quotes. every adds document properties, a page header and footer, a footnote, a comment, hidden text, a link, a bookmark, a group every reader has to skip, a word no reader knows and line, tab, page and section breaks, and each part says where it is. Tika returns the most of them, the header, the footer and the comment among them. LibreOffice, striprtf and RichEdit return the hidden text as text, RichEdit with the address of the link, and pandoc returns the footnote and leaves the hidden text out.
    nesting0 - 100000000How many groups the content sits inside, each one inside the last. 0 puts it straight in the document, and the label stays outside so the file still says what it is. No reader measured lost the content at 10 000 000 levels, but LibreOffice took 18.5 GB of memory over them and pandoc 14.5 GB, against about 2 GB each at 1 000 000.
    links0 - 10000000How many links the document carries, each a HYPERLINK field in a paragraph of its own, above the pictures and the blocks. They go through 17 kinds in turn and then repeat - a link to a bookmark in the document, relative, to the folder above, from the root, absolute with a query and a fragment, absolute with a location, http, without a scheme, percent encoded, an international domain, a port, mailto:, tel:, ftp:, a new window, a screen tip and data: - and the text of each says which it is. Every address is on a domain kept for examples. LibreOffice turns the link without a scheme into a file:// address and rewrites the relative ones from where it saves the document. pandoc 3.12 leaves the bookmark link without an address, pandoc 3.1 and 3.7 drop every link with its text, and RichEdit returns the address of each link in front of its text. LibreOffice took over 11 minutes over a million links. The catalogue of every part has one link of its own, which this does not count.
    inline0 - 100000How many pictures the document shows, each a real file of its format in a paragraph of its own that starts with its name, such as inline_0001.png. They sit above the blocks, at 96 pixels to the inch and never wider than 6 inches. LibreOffice, pandoc and Tika return each file as it was written. RichEdit shows the same picture and writes it out again smaller.
    inline_formatthe id of a picture format, such as png or jpgpngThe format of the pictures, png or jpg - the two picture formats RTF has a name for. Any other format is refused.
    inline_sizea size such as 2mb8kbHow big each picture is. Written in hex it takes twice as many bytes in the document, with a line end every 128 characters. Written binary it takes its own size.
    picture_databinary, hexhexHow the bytes of each picture are written, which changes nothing while the document has no pictures. hex writes them as text, twice as large, the way LibreOffice writes them. binary writes them as they are, so the document is no longer text, and a program that counts braces or reads it as text loses its place. pandoc changes the line ends inside a binary picture, so no png comes out whole, and it can lose the text after the picture or refuse the whole document. LibreOffice, Tika and RichEdit read both.
    +
    +
    + +
    +

    svg Scalable Vector Graphics

    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    SettingAcceptsDefaultWhat it does
    width1 - 20000 pixels800How wide the drawing says it is. Nothing is drawn into pixels here, so a large number costs a few bytes in the file and a great deal of memory in whatever opens it.
    height1 - 20000 pixels600How tall the drawing says it is. The label sits along the bottom edge, so a drawing shorter than that strip carries no visible label.
    contentplaceholder, testtestWhat the picture shows. A test pattern is for checking how a file is read. A placeholder is a flat colour with words in the middle, for laying out a page before the real pictures exist.
    textone line of up to 100 characters{width} × {height}The words in the middle of a placeholder. {width} and {height} become the size of the picture, {index} the number of the file and {index:04} the same number with four digits.
    backgrounda colour such as cccccc or cccccccccThe colour of a placeholder, such as cccccc or ccc. In a recipe write it without # or in quotes, because # starts a comment there.
    foregrounda colour such as cccccc or ccc555555The colour of the words and the guides on a placeholder, written the same way as background.
    guidestrue or falsefalseDraws a frame along the edges of a placeholder, both diagonals and a circle touching its shorter sides, so you can see where a page crops or stretches the picture.
    +
    +
    + +
    +

    targz tar + gzip

    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    SettingAcceptsDefaultWhat it does
    entries0 - 100001How many files the archive holds. When the files are not all alike, describe each kind on its own instead - with Add files inside on Several batches, or contains in a recipe.
    entry_formatthe id of a format, such as png or csvtxtThe format of the files inside.
    entry_sizea size such as 2mb8kbHow big each file inside is.
    compressionbest, default, fast, nonenoneHow hard the files inside are squeezed. The archive still comes out the size you asked for - what changes is how much of it is real content and how much is padding.
    depth0 - 500How many directories deep the files inside sit. 0 puts them all at the top.
    directory_entriestrue or falsefalseWhether the archive also lists the directories themselves. Most file browsers show the same folders either way, so the difference is in the entry list rather than on screen. It matters for readers that only create a directory the archive names.
    entry_mode000, 400, 444, 600, 644, 664, 666, 700, 755, 777644The permissions recorded for each file inside. It is what the archive says, not what the file gets - that depends on who unpacks it and how.
    entry_ownerroot, unset, userunsetWho each file inside belongs to. Leave it unset and the archive names nobody, which is what most archives written by a build carry.
    +
    +
    + +
    +

    tiff Tagged Image File Format

    +
    + + + + + + + + + + + + + + + + +
    SettingAcceptsDefaultWhat it does
    width1 - 20000 pixelsHow wide the picture is. Left out, the picture is sized to fill the bytes you asked for.
    height1 - 20000 pixelsHow tall the picture is. Left out, the picture is sized to fill the bytes you asked for.
    +
    +
    + +
    +

    txt Plain text

    +
    + + + + + + + + + + + + + + + + +
    SettingAcceptsDefaultWhat it does
    encodingutf-16be, utf-16le, utf-8utf-8Which encoding the characters are written in. UTF-16 stores two bytes per character, so a file in it always has an even number of bytes and an odd size is refused.
    bomtrue or falsefalseWhether the file opens with a byte order mark. A reader that has to guess the encoding needs one, and a reader that does not expect it shows it as stray characters at the start of the file.
    +
    +
    + +
    +

    wav Waveform Audio

    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    SettingAcceptsDefaultWhat it does
    sample_rate8000 - 192000 hertz44100How many samples a second the signal carries.
    bit_depth8, 16, 24, 3216How many bits each sample uses.
    channels1 - 82How many channels the signal has, so 1 for mono and 2 for stereo.
    contentnoise, silence, sweep, tonetoneWhat the sound is. A steady tone holds one pitch between 220 and 1099 Hz, chosen by the seed. A rising tone starts at such a pitch and climbs as the file plays. Noise is random hiss, and silence is nothing at all.
    +
    +
    + +
    +

    webm WebM video

    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    SettingAcceptsDefaultWhat it does
    width1 - 16384 pixelsHow wide the picture is. Left out, a size is chosen that fits the bytes you asked for.
    height1 - 16384 pixelsHow tall the picture is. Left out, a size is chosen that fits the bytes you asked for.
    durationa length of time such as 10s10sHow long the film plays. It has to end on a frame, so at 30 frames a second it goes in steps of 100ms.
    change_intervala length of time such as 10s1sHow often the picture changes: the clock in it moves on and the square takes a step. Each change costs a whole picture in bytes. An interval as long as the film or longer keeps one picture throughout.
    frame_rate1, 5, 10, 12, 15, 24, 25, 30, 48, 50, 6030How many frames the film shows each second.
    keyframe_intervala length of time such as 10s1mHow far apart the frames are that a player can start from. Shorter makes skipping through a long film faster and the file bigger, because each of them carries the whole picture twice.
    quality1 - 10060How much detail the picture keeps. Higher looks better and takes more of the file, leaving less room for padding.
    +
    +
    + +
    +

    webp WebP

    +
    + + + + + + + + + + + + + + + + +
    SettingAcceptsDefaultWhat it does
    width1 - 16383 pixelsHow wide the picture is. Left out, the picture is sized to fill the bytes you asked for.
    height1 - 16383 pixelsHow tall the picture is. Left out, the picture is sized to fill the bytes you asked for.
    +
    +
    + +
    +

    xlsx Excel (Office Open XML)

    +
    + + + + + + + + + + + + + + + + +
    SettingAcceptsDefaultWhat it does
    rows1 - 200000 rows1How many rows of cells the sheet holds. The rest of the size you asked for is carried by a part of the package that is not shown.
    columns1 - 32768 columns1How many columns each row has. Above 16384 a spreadsheet may show only the first 16384 and drop the rest without a word.
    +
    +
    + +
    +

    xml Extensible Markup Language

    +
    + + + + + + + + + + + + + + + + +
    SettingAcceptsDefaultWhat it does
    encodingutf-16be, utf-16le, utf-8utf-8Which encoding the characters are written in. UTF-16 stores two bytes per character, so a file in it always has an even number of bytes and an odd size is refused.
    bomtrue or falsefalseWhether the file opens with a byte order mark. A reader that has to guess the encoding needs one, and a reader that does not expect it shows it as stray characters at the start of the file.
    +
    +
    + +
    +

    zip ZIP

    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    SettingAcceptsDefaultWhat it does
    entries0 - 100001How many files the archive holds. When the files are not all alike, describe each kind on its own instead - with Add files inside on Several batches, or contains in a recipe.
    entry_formatthe id of a format, such as png or csvtxtThe format of the files inside.
    entry_sizea size such as 2mb8kbHow big each file inside is.
    compressionbest, default, fast, nonenoneHow hard the files inside are squeezed. The archive still comes out the size you asked for - what changes is how much of it is real content and how much is padding.
    depth0 - 500How many directories deep the files inside sit. 0 puts them all at the top.
    directory_entriestrue or falsefalseWhether the archive also lists the directories themselves. Most file browsers show the same folders either way, so the difference is in the entry list rather than on screen. It matters for readers that only create a directory the archive names.
    passwordthe password, in plain textThe password the archive is locked with. It is written into the manifest as you typed it, because a test that cannot open the file cannot check anything.
    encryptionaes-128, aes-192, aes-256, none, zipcryptononeHow the archive is locked. AES is the WinZip scheme, and some readers cannot open it at all. ZipCrypto is the old one every reader opens and nothing modern trusts, and some of them hand back the encrypted bytes without saying so. A locked archive from this tool is a fixture rather than protection - the key is worked out from the run seed, so the same recipe gives the same archive on any machine, and the password is written into the manifest beside it.
    +
    +
    + +
    + + + + diff --git a/web/public/docs/getting-started/index.html b/web/public/docs/getting-started/index.html new file mode 100644 index 00000000..374a31ef --- /dev/null +++ b/web/public/docs/getting-started/index.html @@ -0,0 +1,284 @@ + + + + + + +Getting Started - Your First Test Files in Five Minutes + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +

    Getting started

    +

    + Five minutes from an installed tfg to a set of test files your tests can rely on. Every + command here runs as it is, on Windows, macOS and Linux. If you have not installed it yet, start + with Install. +

    + +
      +
    1. +

      Make one file of an exact size

      +

      Name the format, the size and the folder. This makes one PNG of exactly two megabytes:

      +
      tfg generate --format png --size 2mb --out ./out
      +
      1 file in 1 target, 2 097 152 B total
      +

      + Sizes count in 1024s, the way a file manager does, so 2mb is 2 097 152 bytes. A + plain byte count works too. The PNG opens in any picture viewer, and beside it is + manifest.json, the record of what the run made and how your system should react + to each file. +

      +
    2. +
    3. +

      Make many files at once

      +

      + Ten thousand log files, each between one and eight kilobytes. The sizes are drawn from the seed, + so the same command gives the same set tomorrow and on any other machine: +

      +
      tfg generate --format log --size-range 1kb-8kb --count 10000 --out ./logs
      +

      + Give each run its own folder. The manifest is the only record of what a run + wrote, so a second run into a folder that holds one is refused rather than written over it. Add + --number-if-taken to put the second run beside the first instead. +

      +
    4. +
    5. +

      Check the files, then remove them

      +

      + verify says whether every file is still there and still the same. + cleanup removes the files the manifest lists and nothing else. Without + --yes it only says what it would remove: +

      +
      tfg verify ./out/manifest.json
      +tfg cleanup ./out/manifest.json
      +tfg cleanup ./out/manifest.json --yes
      +
      out matches ./out/manifest.json: 1 file checked
      +1 file would be removed from out:
      +  remove files_0001.png
      +Nothing was removed. Run the same command with --yes to remove them.
      +1 file removed from out
      +
    6. +
    7. +

      Say what your system should do with the files

      +

      + A test file is only half a test. The other half is what should happen to it. Write it on the + command line and the manifest carries it beside every file: +

      +
      tfg generate --format pdf --size 12mb --expected reject --expected-reason size_limit --out ./too-big
      +

      + For a size limit, the size-boundaries preset makes the whole set at once: files + just under the limit, at it and just over it, each with its expected outcome: +

      +
      tfg generate --preset size-boundaries --limit 10mb --format pdf --out ./limit
      +
    8. +
    9. +

      Make a file that is broken on purpose

      +

      + A damaged file still has the size you asked for, and the manifest expects your system to turn + it away. tfg damage lists the damages this build has: +

      +
      tfg generate --format png --size 2mb --damage zero-head --out ./broken
      +
    10. +
    11. +

      Turn the run into a recipe

      +

      + Once the set is right, write it down. A recipe is a short YAML file you commit beside your + tests, so the files never have to be committed: anyone rebuilds them, byte for byte. +

      +
      # fixtures.yaml
      +version: 1
      +seed: 7741
      +
      +targets:
      +  - id: invoices
      +    format: pdf
      +    count: 25
      +    size: 300kb
      +    name: invoice_{index:04}.pdf
      +    expected: accept
      +
      +  - id: too_big
      +    format: pdf
      +    size: 12mb
      +    expected:
      +      outcome: reject
      +      reason: size_limit
      +
      +output:
      +  dir: ./fixtures
      +
      tfg validate fixtures.yaml
      +tfg generate fixtures.yaml
      +

      + validate checks the recipe and writes nothing. Every key is in + the recipe reference, and the recipe gallery + has ready recipes to start from. +

      +
    12. +
    + +
    +

    Where to go next

    +
      +
    • Test files in CI - a GitHub Actions workflow and a GitLab job that build the set in the pipeline
    • +
    • Test frameworks - the set inside pytest, Playwright, Vitest and node:test
    • +
    • The manifest - every field a test can read
    • +
    • Commands - every flag of every command
    • +
    • Presets - ready sets for common testing questions
    • +
    +
    + +
    + + + + diff --git a/web/public/docs/index.html b/web/public/docs/index.html index 14d55bf6..e348ebf1 100644 --- a/web/public/docs/index.html +++ b/web/public/docs/index.html @@ -147,384 +147,98 @@

    Documentation

    - Everything the tool does, arranged as the questions people actually arrive with. The - README in the repository is the full reference and always matches the - build you downloaded. + How to install tfg, make your first test files, and everything the program takes and writes: every + command and flag, every key of a recipe, every field of the manifest and every setting of every + format. The reference pages are read from the program when the site is built, so they say what the + version you download does.

    -
    -

    What commands are there?

    -

    Each one does a single thing:

    -
    tfg generate    produce files, from a recipe or from flags
    -tfg validate    check a recipe and write nothing
    -tfg verify      check a directory against a manifest
    -tfg cleanup     remove the files a manifest lists
    -tfg recipe fmt  print a recipe in its settled shape
    -tfg preset      build a set of files from a named test question
    -tfg formats     list the formats this build supports
    -tfg damage      list the ways this build can break a file on purpose
    -tfg tool        small things to do with files you already have
    -tfg version     print the tool version
    -tfg license     print the licence and what it means for generated files
    -

    - tfg tool holds the tools for files you already have, such as checking an archive before - unpacking it. Tools describes each one. -

    -
    - -
    -

    How do I generate a single file of an exact size?

    -

    - Name the format, the size and where it goes. Sizes count in 1024s, so 2mb is - 2097152 bytes. A plain byte count works too, so --size 10485761 asks for exactly - that many. -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    The useful flags on generate:

    -
    - - - - - - - - - - - - - - - - - -
    FlagWhat it does
    --format <id>format of the files, for example txt
    --size <size>exact size of every file, such as 10mb or a plain byte count
    --size-range <a-b>a size drawn per file from a range, such as 1kb-8kb. The draw comes from the seed
    --boundary <size>three files around a limit: one byte under, the limit, one byte over
    --count <n>how many files to produce. Default 1
    --name <template>name template, for example invoice_{index:04}.txt
    --out <dir>directory to write into
    --seed <n>run seed. The same seed gives the same bytes
    --set <k>=<v>a format setting, repeatable
    --damage <name>break the files on purpose, repeatable and applied in order. Run tfg damage for the list
    --expected <outcome>accept, reject, sanitize or unspecified
    --dry-runcount and show, write nothing at all
    --jsonwrite the manifest to standard output
    -
    -
    - -
    -

    How do I make a file that is broken on purpose?

    -

    - Every other file this tool writes is correct by construction, which answers two of the three - questions an upload validator asks. --damage answers the third one - does the file - open at all. The file is produced normally and then broken, so it still has the size you asked - for. -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - Settings go after a colon. The flag repeats, and the order you write them in is the order they - are applied. tfg damage lists what this build can do and what each one takes. -

    -

    In a recipe the key is a list, of names or of settings:

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - A damaged file gets expected: reject in the manifest, with the damage recorded - beside it. Two things are refused before anything is written, because each would otherwise - put a file on disk that the manifest describes wrongly: -

    -
      -
    • a file smaller than the damage needs, because it would come out unchanged
    • -
    • - expected: accept beside a damage, because nothing could meet it. Write - sanitize if the system under test is meant to repair the file, or - unspecified if that is the question you are asking -
    • -
    -

    - A third one cannot be known in advance. If a damage runs and moves no byte, that file is - dropped rather than written - the run carries on, says which file it was, and ends with the - partial exit code. -

    -

    - Step by step, with a test that reads the manifest: how to make a corrupt file for testing. -

    -
    - -
    -

    What does a recipe look like?

    -

    - A recipe is a YAML file describing a whole run. Commit it beside your tests and the fixtures stop - being binaries in your repository - anyone can rebuild them, byte for byte, from a file of a few - hundred characters. -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - Every target needs exactly one of size, size-range, boundary - or contains. Two of them is an error and so is none. An invalid recipe writes - no files at all and reports every problem at once rather than the first, each one - naming the setting it is about. -

    -
    - -
    -

    How do I declare what my system should do with a file?

    -

    Short form when the outcome is enough, long form when the reason matters:

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - The outcomes are accept, reject, sanitize and - unspecified. The reasons are a closed list so a report can group by them: - content_malformed, count_limit, dimensions_limit, - duplicate, encoding_invalid, extension_rule, - filename_invalid, filename_too_long, filename_traversal, - malware_signature, mime_mismatch, nesting_depth, - none, size_limit and size_zero. -

    -

    - A reason names the rule in play, not the verdict. That is why the same reason can - sit under either outcome - a file one byte under a limit is accept, and the rule it is - about is still size_limit. -

    -
    - -
    -

    What is in the manifest?

    -

    - It is written next to the files at the end of every run, including a run that was interrupted. One - entry per file: -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "0.6.0-rc1" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - A recipe_hash is added when the run came from a recipe, and preset with - overrides when it came from a preset, so a manifest can always be traced back to what - produced it. -

    -

    - Every entry also carries target_id, the id of the target in the recipe that produced - the file, and summary.by_target counts the files each target came to. A recipe with - several targets can therefore be checked target by target without reading file names. -

    -
    - -
    -

    What is a preset?

    -

    - A ready-made set of files that answers a common testing question, so you do not have to design the - set yourself. Presets are ordinary recipes underneath, and eject prints the recipe so - you can edit it from there. Each preset has a page of its own with what it - usually finds, what is in the set and every setting it takes. -

    +
    +

    Start here, then look things up

    • -

      Empty and minimal

      -

      Does a file that is valid and as small as the format allows get through?

      -

      empty-and-minimal

      +

      Install

      +

      Download the command line tool and the desktop window, check that the archive is the one this project published, or run it from Docker, npm, pip or Go.

    • -
    • -

      File name handling

      -

      Will my system store, show and give back a file name it did not expect?

      -

      filename-handling

      +
    • +

      Getting started

      +

      Make one file of an exact size, then ten thousand, check them against the manifest, remove them, and turn the run into a recipe you can commit.

    • -
    • -

      Picture sizes

      -

      Does my system take pictures at the sizes screens and platforms use?

      -

      picture-sizes

      +
    • +

      Commands

      +

      Every command of the tfg command line with every flag it takes, its default and what it does, read from the program's own help, and every exit code.

      +
    • +
    • +

      Writing recipes

      +

      How to write a recipe: every key it accepts, the ways to give a size, name templates, expected outcomes and reasons, damage, archive contents and presets.

    • -

      Size boundaries

      -

      Is a size limit enforced exactly where it is declared?

      -

      size-boundaries

      +

      Recipe gallery

      +

      Ready recipes for common test sets: image and document uploads, table imports, archives, email, media, CI and bulk files. Download one, run it, change it.

      +
    • +
    • +

      Manifest

      +

      Every field of the manifest written beside the files: the run, the summary, and each file with its hash, its settings and how your system should react to it.

    • -

      Tabular import

      -

      Does my table import survive what real tools export?

      -

      tabular-import

      +

      Format settings

      +

      Every setting each format takes, such as pages, picture size, delimiter or encoding, with the values it accepts, its default and what it changes in the file.

    • -

      Text encoding

      -

      Does my reader know which encoding a file is in, or is it guessing?

      -

      text-encoding

      +

      Test frameworks

      +

      Use generated test files inside your tests: the pytest plugin and the npm package for Playwright, Vitest and node:test, with what each file should be met with.

      +
    • +
    • +

      Desktop app

      +

      The window of Testing Files Generator screen by screen: one batch, presets, several batches, tools and preferences, with what each of them does.

    • -

      Upload validation

      -

      Does my upload form take what it should and turn the rest away?

      -

      upload-validation

      +

      Tools

      +

      Offline tools for files you already have: see whether an archive is safe to unpack, zip slip and zip bomb included, and check or write SHA-256 checksums.

    -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show tells you what the set would cost before you build it, and says outright when a - number is a placeholder of ours rather than a limit of yours. -

    -
    -

    What do the exit codes mean?

    -

    - Every ending has its own code, machine readable output goes to standard output, and a failed run - prints nothing there. The table is a frozen contract - changing what a code means requires a major - version bump. -

    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    CodeMeaning
    0Everything worked.
    1An unexpected error inside the tool.
    2Wrong command or flag.
    3The recipe is not valid.
    4The format cannot do what was asked.
    5A read or a write failed.
    6Not enough disk space.
    7verify found a mismatch.
    8The run finished but not everything was produced.
    130Interrupted with Ctrl+C.
    143Stopped by a signal, which is what a CI timeout looks like.
    -
    -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - A run stopped with Ctrl+C still leaves a manifest and never leaves a half written file behind, so - a cancelled job can still be cleaned up by the next one. -

    -

    - Ready workflows for GitHub Actions and GitLab CI: how to generate test files in a CI pipeline. -

    +
    +

    What the tool does, by topic

    +
      +
    • +

      Formats

      +

      Every file format this generator produces, the smallest file each one can be, and the settings each one accepts. All 32 open in the software that owns them.

      +
    • +
    • +

      Presets

      +

      Ready-made sets of test files, each answering one testing question: upload limits, file names, encodings, table imports, empty files and upload validation.

      +
    • +
    • +

      Corrupt test files

      +

      Make a file that is broken on purpose, at the exact size you ask for, with a manifest saying your system should reject it. For testing upload validation and parsers.

      +
    • +
    • +

      Sample files

      +

      Download sample files for testing: one of every format at 1 MB, corrupt PDF, Word and Excel files, CSV tables and placeholder images, each with its SHA-256.

      +
    • +
    • +

      File upload test cases

      +

      Test cases for a file upload: the size limit, empty and corrupt files, the wrong type, unexpected file names and archives, each with the file that tests it.

      +
    • +
    • +

      Test files in CI

      +

      Generate test files in the pipeline instead of committing binaries: a GitHub Actions workflow, a GitLab job, exit codes that fail the build and the PowerShell catch.

      +
    • +
    • +

      Exact size

      +

      fsutil, dd, truncate and mkfile, each measured on the system it belongs to - and why a file made that way is not a PDF or a PNG when a test needs one.

      +
    • +
    -
    -

    Is there a desktop window?

    -

    - Yes, the same engine with a window on it, for the testing that is not scripted. It is not a cut - down version: a test compares the two interfaces capability by capability, and anything only one of - them can do has to be declared and justified rather than quietly drifting apart. -

    +
    +

    Still stuck?

    - The screens are one batch, presets, several batches at once, and about. It shows what a run would - cost before writing anything, reports progress while it runs, and can be cancelled part way without - leaving a half written file behind. It does not open a recipe file yet - recipes are a command line - thing for now, and the window builds its batches in the form. + tfg <command> --help says what a command takes, in the terminal. Every refusal names + the setting it is about, why, and a value that would work. If something does not behave the way a page + here says, open an issue. That is a bug in the page or in the program.

    diff --git a/web/public/docs/install/index.html b/web/public/docs/install/index.html new file mode 100644 index 00000000..627f0d05 --- /dev/null +++ b/web/public/docs/install/index.html @@ -0,0 +1,338 @@ + + + + + + +Install Testing Files Generator on Windows, macOS, Linux or Docker + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +

    Install

    +

    + There are two programs. tfg is the command line, for scripts and pipelines. + tfg-gui is the desktop window, for testing by hand. Both make the same files from the + same settings. Pick the way of installing that fits where you will run them. +

    + +
    +

    The short answer

    +

    + Download the archive for your system from the releases page, unpack it and run + tfg version. Everything runs on your machine, and the program never connects to the + internet. +

    +
    + +
    +

    Download a binary

    +

    + Take the archive for your system from the releases page, unpack it anywhere and run the program + inside. Nothing else is needed. These are the systems each program is built for: +

    +
    + + + + + + + + + + + + + + + + + + + + + + + + + +
    SystemCommand lineDesktop window
    Windowsamd64, arm64amd64
    Linuxamd64, arm64amd64
    macOSarm64arm64
    +
    +

    + The archives are named after the program, the version, the system and the processor, such as + tfg_0.5.0_linux_amd64.tar.gz or + tfg-gui_0.5.0_windows_amd64.zip. On Windows x64 the release also has an + installer, tfg-setup_0.5.0_windows_amd64.msi. +

    +

    + The Windows and macOS programs are signed, so they start without a warning about an unknown + developer. The Linux ones are not, because desktop Linux has nothing to sign them with. +

    + +

    Free and open source, GPL-3.0. Nothing to sign up for. The Windows and macOS downloads are signed and start without a warning.

    +
    + +
    +

    Check that the archive is the one this project published

    +

    + Every release has a verify-SHA256SUMS.txt with the checksum of every archive. A + matching checksum says the archive arrived whole. With the GitHub command line installed, the + attestation also says the release workflow of this project made it. +

    +
    tfg_version=0.5.0
    +archive=tfg_${tfg_version}_linux_amd64.tar.gz
    +url=https://github.com/donislawdev/TestingFilesGenerator/releases/download/v$tfg_version
    +curl -fsSLO "$url/$archive"
    +curl -fsSLO "$url/verify-SHA256SUMS.txt"
    +grep " $archive\$" verify-SHA256SUMS.txt | shasum -a 256 -c
    +gh attestation verify "$archive" --repo donislawdev/TestingFilesGenerator --predicate-type https://spdx.dev/Document/v2.3
    +

    + Without shasum, tfg tool checksum does the same on any system once you + have one copy of tfg you trust: tfg tool checksum <archive> --expected <sum>. +

    +
    + +
    +

    Run it from Docker

    +

    + The command line also comes as an image for Linux, on x64 and Arm. It holds the program from the + release archive and nothing else, and it runs with no network. Name the version rather than + latest, so the same recipe gives the same files next month too. +

    +
    docker run --rm --network none -v "${PWD}:/work" ghcr.io/donislawdev/tfg:0.5.0 generate --format pdf --size 1mb
    +

    + The files land in the current directory. On Linux add --user "$(id -u):$(id -g)", so + the image may write there and the files belong to you. With no directory mounted, the run stops + with exit code 5 rather than writing files that disappear with the container. +

    +
    + +
    +

    Install it with npm, for tests in Node

    +

    + The testing-files-generator package gives Playwright, Vitest and + node:test a generated set of files and what your system should do with each, and + installs the tfg of the same release for your system. It comes for Windows and Linux on x64 and + Arm, and for macOS on Apple silicon. +

    +
    npm install --save-dev testing-files-generator
    +npx tfg version
    +

    How to use it in a test: Test frameworks.

    +
    + +
    +

    Install it with pip, for tests in Python

    +

    + The testing-files-generator package gives pytest and unittest a generated set of + files and what your system should do with each, and installs the tfg of the same release for + your system. pytest finds its plugin on its own. uv installs it as well. +

    +
    pip install testing-files-generator
    +tfg version
    +

    + If tfg is not found, the folder pip puts programs in is not on your + PATH, and python -m testing_files_generator version runs the same tfg. +

    +
    + +
    +

    Install it with Go

    +

    With Go installed, this builds the command line and puts it in your Go bin folder:

    +
    go install -tags noasm github.com/donislawdev/TestingFilesGenerator/cmd/tfg@latest
    +

    + The tag is not optional. It turns off a path of the AVIF encoder that reads past the end of a + buffer on some picture sizes. Built without it, the program does not compile, and says why. The + files are the same either way. +

    +
    + +
    +

    Build it from source

    +

    It needs Go and nothing else:

    +
    git clone https://github.com/donislawdev/TestingFilesGenerator
    +cd TestingFilesGenerator
    +go build -tags "$(cat .github/build-tags)" ./cmd/tfg
    +

    + The window is a second program, go build -tags "$(cat .github/build-tags)" ./cmd/tfg-gui. + It draws through OpenGL and reaches it through C, so it needs a C compiler on the system it is + built for. Built without one, it still compiles, and says on start that it has no window and + that everything is on the command line. +

    +
    + +
    +

    When the window does not open

    +

    + The window needs OpenGL 2.1 to draw. On Windows the archive carries a software renderer, in an + opengl folder next to tfg-gui.exe, for machines whose graphics driver + offers none: a virtual machine without 3D acceleration, a remote desktop, a server. The window + uses it by itself when the driver refuses, and says so on its About screen. Keep the folder next + to the program. +

    +

    + tfg-gui --software-gl uses the software renderer on any Windows machine, which shows + the window the way a machine without a driver sees it. Linux and macOS have what the window + needs, so there the flag changes nothing. The command line needs no graphics at all and does + everything the window does. +

    +
    + +
    + + + + diff --git a/web/public/docs/manifest/index.html b/web/public/docs/manifest/index.html new file mode 100644 index 00000000..55770ade --- /dev/null +++ b/web/public/docs/manifest/index.html @@ -0,0 +1,347 @@ + + + + + + +Manifest Reference - What manifest.json Says About Each Test File + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +

    Manifest

    +

    + Every run writes manifest.json beside its files. It lists every file with its size, its + SHA-256 and what your system should do with it, so a test reads the expectation instead of hard + coding it. It is written even when a run is stopped part way. +

    + +
    +

    What a manifest looks like

    +

    This is the manifest of tfg generate --format png --size 2mb --out ./out, shortened:

    +
    {
    +  "manifest_version": "1.0",
    +  "tool": { "name": "testing-files-generator", "version": "0.6.0-rc1" },
    +  "run": {
    +    "id": "run_b359aa8d94",
    +    "seed": 0,
    +    "command": "tfg generate --format png --size 2mb --out ./out",
    +    "platform": { "os": "windows", "arch": "amd64" },
    +    "complete": true
    +  },
    +  "summary": {
    +    "file_count": 1,
    +    "total_bytes": 2097152,
    +    "by_format": { "png": 1 },
    +    "by_expected": { "unspecified": 1 }
    +  },
    +  "files": [
    +    {
    +      "path": "files_0001.png",
    +      "bytes": 2097152,
    +      "format": "png",
    +      "fidelity": "full",
    +      "determinism": "byte",
    +      "seed": "8dc2d18c",
    +      "hashes": { "sha256": "1a1f7c..." },
    +      "properties": { "width": 640, "height": 480 },
    +      "expected": {
    +        "outcome": "unspecified",
    +        "detail": "No expectation was declared for this file.",
    +        "confidence": "policy_dependent"
    +      }
    +    }
    +  ]
    +}
    +
    + +
    +

    How a test reads it

    +

    + Go through files, give each file to your system, and compare what it did with + expected.outcome. When send_as is there, give the file under that name. A + sketch in Python, with your own upload in place of upload: +

    +
    import json, pathlib
    +
    +folder = pathlib.Path("fixtures")
    +manifest = json.loads((folder / "manifest.json").read_text(encoding="utf-8"))
    +for f in manifest["files"]:
    +    if f["expected"]["outcome"] == "unspecified":
    +        continue
    +    result = upload(folder / f["path"], name=f.get("send_as", f["name"]))
    +    assert result == f["expected"]["outcome"], f["path"]
    +

    + The packages for pytest and Node do this for you: Test frameworks. + An outcome of unspecified means the right reaction depends on how your system is set up. + policy_options lists the answers left open, for a test that settles them by your policy. +

    +
    + +
    +

    Every field

    +

    + Every field a manifest can carry, read from the program when this page is built. [] + stands for each entry of a list, and * for each key of an object whose keys are yours, + such as the names of the flags in run.overrides. A field marked as present only in some + runs is left out of the others rather than written empty. +

    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    FieldWhat it holds
    manifest_versionThe version of the manifest format, 1.0. New fields are added without changing it, so a reader ignores the fields it does not know.
    generated_atWhen the manifest was written, in UTC.
    toolWhat made the files.
    tool.nameAlways testing-files-generator.
    tool.versionThe version of tfg that made the files.
    tool.goThe version of Go tfg was built with, so a hash that changed after an upgrade can be traced to it.
    tool.generatorsThe version of the generator of each format the run used, by format. It moves when the bytes a generator writes change.
    runThe settings that shaped this run.
    run.idAn identifier of this run.
    run.seedThe seed of the run. The same seed and the same settings give the same files.
    run.commandThe command that started the run, as it was typed.
    run.platformWhere the run happened.
    run.platform.osThe operating system, such as windows, linux or darwin.
    run.platform.archThe processor architecture, such as amd64 or arm64.
    run.completefalse when the run stopped early, for example after Ctrl+C. The manifest is written even then, so cleanup can remove what was made.
    run.recipe_hashThe hash of the recipe in its settled shape, so reformatting the recipe keeps it. Present when the run came from a recipe.
    run.overridesThe values a flag took over from the recipe, by name. Present when a flag replaced a value of the recipe.
    run.overrides.*.from_recipeThe value the recipe gave.
    run.overrides.*.from_flagThe value the flag gave, which the run used.
    run.presetThe preset the run came from. Present only for a run of a preset.
    run.preset.idThe id of the preset.
    run.preset.questionThe question the preset answers.
    run.preset.parametersEvery setting of the preset as the run used it, the ones you gave and its defaults together.
    run.preset.defaultedThe settings you did not give, which took the default of the preset. A limit that came from a default is not the limit of your system.
    run.instructionsThe name of the file written beside the manifest that says in words what each file is and why it is in the set. Present when a file has a purpose.
    summaryCounts over the whole run, for a quick check.
    summary.file_countHow many entries the manifest has. A run stopped part way lists only the files it finished or that failed, so it can be lower than the files that were planned.
    summary.total_bytesHow many bytes the run wrote to disk, in all.
    summary.materializedHow many files are on disk. Lower than file_count when a name could not be written or a file failed.
    summary.by_formatHow many files of each format.
    summary.by_expectedHow many files of each outcome.
    summary.by_targetHow many files each target made, by target id.
    filesOne entry for each file of the run.
    files[].idThe handle of the file in this manifest, such as f_0001, numbered across the whole run.
    files[].pathWhere the file is, relative to the directory of the manifest. verify and cleanup find the file by this.
    files[].nameThe file name, the last part of path.
    files[].send_asThe name to give the file to your system under, when the recipe asked for one no disk stores. Present only then.
    files[].materializedWhether the file is on disk. A name the system refused is still a test case, and still has its entry.
    files[].target_idThe id of the target the file came from.
    files[].bytesThe size of the file in bytes.
    files[].formatThe format of the file.
    files[].fidelityHow faithful the file is to its format. tfg formats says it for each format.
    files[].hashesThe hashes of the file.
    files[].hashes.sha256The SHA-256 of the file, which verify compares.
    files[].seedThe seed this file was made from, which comes from the seed of the run and the id of the target.
    files[].generatorThe generator that made the file.
    files[].generator.nameThe name of the generator.
    files[].generator.versionThe version of the generator.
    files[].determinismWhether the same seed gives the same bytes, byte, or only the same size.
    files[].propertiesThe settings of the format the file was made with, such as its width and height.
    files[].expectedWhat your system should do with the file.
    files[].expected.outcomeaccept, reject, sanitize or unspecified.
    files[].expected.reasonThe rule in play, from the closed list, such as size_limit.
    files[].expected.detailThe expectation in words.
    files[].expected.confidencecertain, or policy_dependent when the right reaction depends on how your system is set up.
    files[].expected.policy_optionsThe answers an outcome that depends on your system leaves open, for a test that settles it by your own policy.
    files[].groupThe group the recipe or the preset gave the file.
    files[].purposeWhat the file is and why it is in the set, in words.
    files[].label_embeddedWhether the file carries the label that says which run made it.
    files[].damageWhat was broken on purpose, in the order it was done. Absent for a file nothing damaged.
    files[].damage[].typeThe damage, such as truncate.
    files[].damage[].settingsIts settings as the run used them, the defaults included.
    files[].damage[].cutWhere a cut fell in the file. Present for truncate.
    files[].damage[].cut.inWhat the first byte cut away was part of: content, padding, structure or end.
    files[].damage[].cut.content_bytesHow long the content of the whole file was, where that is known.
    files[].damage[].cut.content_kept_bytesHow much of the content is still in the file.
    files[].notesThings worth knowing about this file, such as a label that did not fit.
    files[].notes[].codeA short code for the note, such as cut_in_padding.
    files[].notes[].detailThe note in words.
    files[].failedtrue for a file the run could not make. The run carries on and ends with exit code 8.
    files[].errorWhy the file could not be made.
    +
    +
    + +
    +

    What else is written beside it

    +

    + When the files of a run have a purpose, from a preset or from purpose in a recipe, a + second file is written beside the manifest, manifest.instructions.md. It says in words + what each file is and why it is in the set, for the person running the test by hand. + verify and cleanup know about it. +

    +

    + tfg verify manifest.json checks that every file is still there and still has its SHA-256. + tfg cleanup manifest.json --yes removes exactly the files the manifest lists, and + nothing else, so it is safe in a folder that holds other things too. +

    +
    + +
    +

    Can I rely on the format?

    +

    + Yes. manifest_version is 1.0, and the format grows only by adding fields. + A field never changes its meaning within a version, so a reader written today keeps working if it + ignores the fields it does not know. +

    +
    + +
    + + + + diff --git a/web/public/docs/recipes/index.html b/web/public/docs/recipes/index.html new file mode 100644 index 00000000..24a75e33 --- /dev/null +++ b/web/public/docs/recipes/index.html @@ -0,0 +1,427 @@ + + + + + + +Recipe Reference - Every Key of a Test File Recipe in YAML + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +

    Recipes

    +

    + A recipe is a YAML file that describes a whole run: which files, how many, how large, and what your + system should do with each. Commit it beside your tests and the test files stop being binaries in + your repository. Anyone rebuilds them from the recipe, byte for byte. +

    + +
    +

    What a recipe looks like

    +
    # fixtures.yaml
    +version: 1
    +seed: 7741
    +
    +defaults:
    +  label: true
    +
    +targets:
    +  - id: invoices
    +    format: pdf
    +    count: 25
    +    size: 300kb
    +    name: invoice_{index:04}.pdf
    +    properties:
    +      pages: 3
    +      page_size: a4
    +    expected: accept
    +
    +  - id: over_the_limit
    +    format: png
    +    count: 2
    +    size: 12mb
    +    expected:
    +      outcome: reject
    +      reason: size_limit
    +
    +  - id: bundle
    +    format: zip
    +    contains:
    +      - format: txt
    +        count: 200
    +        size: 4kb
    +
    +output:
    +  dir: ./fixtures
    +  manifest: manifest.json
    +
    tfg validate fixtures.yaml
    +tfg generate fixtures.yaml
    +

    + Every recipe has a version and a list of targets. A target is one kind of + file: it needs an id, a format and exactly one of size, + size-range, boundary or contains. Two of them is an error, + and so is none. +

    +

    + An invalid recipe writes no files at all. validate and + generate report every problem at once, each naming the key it is about, so one run + shows everything to fix. +

    +
    + +
    +

    Keys of the whole recipe

    +

    + Every key a recipe accepts is listed here, read from the program when this page is built. A key + marked as not built yet is refused with a message saying so, never ignored. +

    +
    + + + + + + + + + + + + + + + + + + + + +
    KeyWhat it does
    allow_nondeterministicConsent to formats whose bytes differ from run to run. Every format of this build repeats to the byte, so true is refused for now and the line can be left out.
    defaultsSettings every target takes unless it says otherwise.
    defaults.fillHow the content of the files is made. Not built yet: a recipe with this key is refused, and the content always comes from the seed.
    defaults.labelWhether each file carries a short label saying which run made it. true unless you say otherwise. The label is written so that the file stays valid.
    engineThe version of tfg the recipe needs. Not built yet: a recipe with this key is refused, and the manifest records the version that ran.
    extendsA preset to build on, written as preset:size-boundaries. Its files come first, and the targets of the recipe are added after them.
    localeThe language of the generated content. Only en is available, so any other value is refused, and the line can be left out.
    outputWhere the run writes.
    output.dirThe directory for the files and the manifest. A relative path is read from the directory you run in, not from the one the recipe is in. --out replaces it.
    output.manifestThe file name of the manifest. manifest.json unless you say otherwise.
    output.split_thresholdSplitting a large manifest into several files. Not built yet: a recipe with this key is refused, and the manifest is always one file.
    policyRules for settling the expectations that depend on your system. Not built yet: a recipe with this key is refused. Write expected on each target instead.
    seedThe number every byte of the run comes from. The same seed gives the same files on any machine. 0 unless you say otherwise.
    targetsThe list of things to produce. Every target needs an id, a format and exactly one of size, size-range, boundary or contains.
    versionThe version of the recipe format. Required, and 1 in this build.
    withThe settings of the preset named in extends, written the way its flags take them, such as limit: 5mb. A setting left out takes its default, and the manifest says so.
    +
    +
    + +
    +

    Keys of a target

    +
    + + + + + + + + + + + + + + + + + + + + +
    KeyWhat it does
    targets.boundaryThree files around a limit: one byte under it, the limit itself and one byte over it. Written as a size, such as 5mb.
    targets.containsFor an archive: the files inside it, as a list of entries, each with a format, a count and a size.
    targets.countHow many files the target makes. 1 unless you say otherwise.
    targets.damageWays to break the files on purpose, applied in the order listed. Each one is a name, such as zero-head, or a type with its settings. tfg damage lists them.
    targets.expectedWhat your system should do with these files: accept, reject, sanitize or unspecified, alone or with a reason. The manifest carries it beside every file.
    targets.fillHow the content of these files is made. Not built yet: a recipe with this key is refused.
    targets.formatThe format of the files, by its id, such as pdf or png. tfg formats lists them.
    targets.groupA name of your own for the kind of case these files are. The manifest carries it, so a report can group by it.
    targets.idThe name of the target. It is unique in the recipe, the seeds of its files come from it, and the manifest names it beside every file in target_id.
    targets.labelWhether these files carry the label. Overrides defaults.label for this target alone.
    targets.nameThe template for the file names, such as invoice_{index:04}.pdf. {index:04} is the number of the file, four digits or more, and the only placeholder there is.
    targets.propertiesThe settings of the format, such as pages for a PDF or width and height for a picture. The page of format settings lists every one.
    targets.purposeA sentence or two on what these files are and why they are in the set. The manifest carries it, and the instructions written beside the manifest are made from it.
    targets.send-asThe name to give these files to your system under, when it is one no disk stores, such as ../climbed_out.jpg. The file keeps an ordinary name on disk, and the manifest carries this one in send_as.
    targets.sizeThe exact size of every file, such as 300kb, 10mb or a plain byte count. Units count in 1024s. smallest makes a picture as small as it can be at its width and height.
    targets.size-rangeA size drawn for each file from a range, such as 1kb-8kb. The draw comes from the seed, so the same seed gives the same sizes.
    +
    +
    + +
    +

    How to write a size

    +

    + A size is a number with a unit: b, kb, mb, gb + or tb. Units count in 1024s, the way a file manager does, so 10mb is + 10 485 760 bytes. kib, mib, gib and tib mean the + same and say so. A fraction works, as in 1.5mb, and so does a plain byte count, as in + 10485761. +

    +
      +
    • size: 300kb - every file of the target is exactly that large
    • +
    • size-range: 1kb-8kb - each file gets a size from the range, drawn from the seed
    • +
    • boundary: 5mb - three files: one byte under, the limit itself, one byte over
    • +
    • size: smallest - a picture as small as it can be at the width and height you set
    • +
    +

    + When a format cannot reach a size, the run is refused before anything is written, with the + smallest size the format can make and what to change. A size is never rounded quietly. +

    +
    + +
    +

    How to name the files

    +

    + name is a template. {index:04} is the number of the file, padded to four + digits, and it is the only placeholder there is. Without a template a file is named after its target, + as invoices_0001.pdf. +

    +
    name: invoice_{index:04}.pdf
    +

    + A name no disk stores, such as ../climbed_out.jpg, goes in send-as. The file + keeps an ordinary name on disk, and the manifest carries the other one in send_as, for + the test to upload it under. +

    +
    + +
    +

    How to declare what your system should do

    +

    Short form, when the outcome is enough. Long form, when the reason matters:

    +
    expected: accept
    +
    expected:
    +  outcome: reject
    +  reason: size_limit
    +

    + The outcomes are accept, reject, sanitize, unspecified. + The reasons are a closed list, so a report can group by them: + content_malformed, count_limit, dimensions_limit, duplicate, encoding_invalid, extension_rule, filename_invalid, filename_too_long, filename_traversal, malware_signature, mime_mismatch, nesting_depth, none, size_limit, size_zero. +

    +

    + A reason names the rule in play, not the verdict. That is why one reason can sit + under either outcome: a file one byte under a limit is accept, and the rule it is about + is still size_limit. Where the right reaction depends on how your system is set up, the + manifest says unspecified and explains why, rather than guessing. +

    +
    + +
    +

    How to break files on purpose

    +

    + damage is a list, applied in the order written. Each entry is a name, or a + type with its settings. The file still has the size you asked for: +

    +
    targets:
    +  - id: broken
    +    format: png
    +    count: 5
    +    size: 2mb
    +    damage:
    +      - zero-head
    +      - type: truncate
    +        missing: 30
    +    expected:
    +      outcome: reject
    +      reason: content_malformed
    +

    + tfg damage lists the damages and what each takes. Asking for accept beside a + damage that breaks the rules of the format is refused, because nothing could meet it. More in + Corrupt test files. +

    +
    + +
    +

    How to fill an archive

    +

    + contains lists what goes inside a ZIP or a TAR.GZ. Each entry has a format, a count and + a size, and every file inside is a real file of its format. The archive is as large as what it + holds: +

    +
    targets:
    +  - id: bundle
    +    format: zip
    +    contains:
    +      - format: pdf
    +        count: 3
    +        size: 200kb
    +      - format: csv
    +        count: 10
    +        size: 8kb
    +

    + The settings of the archive itself, such as compression, depth or a password, are in + Format settings. +

    +
    + +
    +

    How to build on a preset

    +

    + A recipe can start from the set of a preset and add its own targets after it. with gives + the preset its settings, written the way its flags take them: +

    +
    version: 1
    +seed: 7
    +extends: preset:size-boundaries
    +with:
    +  limit: 5mb
    +  format: png
    +targets:
    +  - id: our-legacy-format
    +    format: tiff
    +    count: 1
    +    size: 3mb
    +

    + This makes the same files as tfg preset eject size-boundaries --limit 5mb --format png + with the extra target typed under it. A target whose id the preset already uses is + refused, never quietly replaced. The manifest names the preset, and lists the settings you left to + its defaults. +

    +
    + +
    +

    How to check a recipe before a commit

    +
    tfg validate fixtures.yaml
    +tfg recipe fmt fixtures.yaml --check
    +

    + validate says whether the recipe makes sense and what it would make, and writes nothing. + recipe fmt --check says whether the file is laid out in its settled shape, and + recipe fmt -w lays it out, comments kept. Run both in a pre-commit hook. +

    +

    + Ready recipes to download and change are in the recipe gallery. +

    +
    + +
    + + + + diff --git a/web/public/docs/test-frameworks/index.html b/web/public/docs/test-frameworks/index.html new file mode 100644 index 00000000..dceb913c --- /dev/null +++ b/web/public/docs/test-frameworks/index.html @@ -0,0 +1,315 @@ + + + + + + +Test Files in pytest, Playwright, Vitest and node:test + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +

    Test frameworks

    +

    + Two packages bring the files into your tests: testing-files-generator on PyPI for pytest + and unittest, and the package of the same name on npm for Playwright, Vitest and + node:test. Each gives you one test for each file of a set, named by what the file should + meet, and fails a test with a sentence that says what went wrong. +

    + +
    +

    How it works

    +

    + You choose a set, usually a preset. The package plans it and gives you its files. Each test hands + its file to your system and ends with one line saying what your system did. A file with no right + answer is skipped, never passed. tfg comes inside both packages, works offline and never connects + to the network. +

    +
    + +
    +

    pytest

    +
    pip install testing-files-generator
    +

    + pytest finds the plugin on its own. Python 3.10 or later. This test sends every file of the + upload-validation preset to an upload endpoint with + requests, around a limit of 2 MB: +

    +
    # tests/test_upload.py
    +import pytest
    +import requests
    +from testing_files_generator import file_set
    +
    +uploads = file_set(preset="upload-validation", options={"limit": "2mb", "bulk": 0})
    +
    +
    +@pytest.mark.parametrize("file", uploads.params())
    +def test_upload(file):
    +    with open(file.path(), "rb") as body:
    +        response = requests.post("http://localhost:3000/upload", files={"file": (file.send_as, body)}, timeout=30)
    +    assert response.status_code < 500, "a server error is not a refusal"
    +    file.check("accept" if response.ok else "reject")
    +

    Each test is named by its file and what the file expects. Listing them writes no file:

    +
    pytest --collect-only -q
    +
    tests/test_upload.py::test_upload[2mb_under_1b.jpg - expected accept]
    +tests/test_upload.py::test_upload[2mb_at_limit.jpg - expected accept]
    +tests/test_upload.py::test_upload[2mb_over_1b.jpg - expected reject (size_limit)]
    +tests/test_upload.py::test_upload[pdf_as_jpg.jpg - expected reject (mime_mismatch)]
    +...
    +

    + Every test carries its outcome and its group as markers, so pytest -m reject or + pytest -m size-limit runs part of the set. Without pytest, the same set works in + unittest or any runner that makes tests in a loop. +

    +
    + +
    +

    Playwright

    +
    npm install --save-dev testing-files-generator
    +

    This spec uploads every file through the form, the way a person does:

    +
    // tests/upload.spec.ts
    +import { test, expect } from '@playwright/test';
    +import { fileSet } from 'testing-files-generator';
    +
    +const uploads = fileSet({ preset: 'upload-validation', options: { limit: '2mb', bulk: 0 } });
    +
    +for (const file of uploads.files) {
    +  test(file.title, file.details, async ({ page }) => {
    +    test.skip(file.unspecified, file.whyUnspecified);
    +    await page.goto('/upload');
    +    await page.getByLabel('File').setInputFiles(await file.path());
    +    await page.getByRole('button', { name: 'Upload' }).click();
    +    const status = page.getByRole('status');
    +    await expect(status).toHaveText(/Uploaded|Refused/);
    +    file.check((await status.textContent())?.includes('Uploaded') ? 'accept' : 'reject');
    +  });
    +}
    +

    + Only the lines that upload and read the answer are about your app. Change them to however your + app takes a file. Wait for an answer your app gives on purpose, as Uploaded or + Refused here, so a page that shows an error fails the test rather than passing as a + refusal. npx playwright test --grep @reject runs part of the set. +

    +
    + +
    +

    Vitest and node:test

    +

    + The package imports nothing from Playwright, so any runner that declares tests in a loop works. + With Vitest: +

    +
    import { test, expect } from 'vitest';
    +import { openAsBlob } from 'node:fs';
    +import { fileSet } from 'testing-files-generator';
    +
    +const uploads = fileSet({ preset: 'upload-validation', options: { limit: '2mb', bulk: 0 } });
    +
    +for (const file of uploads.files) {
    +  test.skipIf(file.unspecified)(file.title, async () => {
    +    const body = new FormData();
    +    body.append('file', await openAsBlob(await file.path()), file.sendAs);
    +    const response = await fetch('http://localhost:3000/upload', { method: 'POST', body });
    +    expect(response.status, 'a server error is not a refusal').toBeLessThan(500);
    +    file.check(response.ok ? 'accept' : 'reject');
    +  });
    +}
    +

    + With the runner built into Node, node --test, the loop is the same, with + test(file.title, { skip: file.unspecified && file.whyUnspecified }, ...). +

    +
    + +
    +

    Telling the set what your system did

    +

    + check takes accept, reject or sanitize and fails + the test when the file expected something else. When your system says why it turned a file away, + pass the reason as well, and a file turned away for the wrong rule fails too. In Python: +

    +
    file.check({"outcome": "reject", "reason": response.json().get("reason")})
    +

    + A server error is not a refusal, so check the status before check, as the examples do. + A file sent under another name, such as ../climbed_out.jpg, gives that name in + send_as, or sendAs in Node, and the examples upload it under that name. +

    +
    + +
    +

    Your own set

    +

    + Any preset works in place of upload-validation, with its settings in + options. For a set of your own, write a recipe and name it: +

    +
    uploads = file_set(recipe="tests/fixtures.yaml")
    +
    const uploads = fileSet({ recipe: path.join(__dirname, 'fixtures.yaml') });
    +

    + Recipes says how to write one, and the recipe + gallery has ready ones to start from. +

    +
    + +
    +

    Everything else

    +

    + Each package has a full guide of its own, with where the files are kept, CI, every option and what + to do when something goes wrong: + testing-files-generator on PyPI and + testing-files-generator on npm. +

    +
    + +
    + + + + diff --git a/web/public/es/documentacion/index.html b/web/public/es/documentacion/index.html index 68f149cd..0eb87acc 100644 --- a/web/public/es/documentacion/index.html +++ b/web/public/es/documentacion/index.html @@ -147,387 +147,93 @@

    Documentación

    - Todo lo que hace la herramienta, ordenado según las preguntas con las que la gente llega de verdad. - El README del repositorio es la referencia completa y siempre - coincide con la versión que descargaste. + Cómo instalar tfg, crear tus primeros archivos de prueba y todo lo que el programa acepta y escribe: cada comando y cada opción, cada clave de una receta, cada campo del manifiesto y cada ajuste de cada formato. Estas páginas están en inglés, porque se generan a partir del propio programa cada vez que se construye el sitio, y por eso siempre dicen lo que hace la versión que descargas.

    -
    -

    ¿Qué comandos hay?

    -

    Cada uno hace una sola cosa:

    -
    tfg generate    producir archivos, desde una receta o desde opciones
    -tfg validate    comprobar una receta sin escribir nada
    -tfg verify      comprobar un directorio contra un manifiesto
    -tfg cleanup     eliminar los archivos que lista un manifiesto
    -tfg recipe fmt  imprimir una receta en su forma normalizada
    -tfg preset      construir un conjunto de archivos a partir de una pregunta de prueba con nombre
    -tfg formats     listar los formatos que admite esta versión
    -tfg damage      listar las formas en que esta versión puede romper un archivo a propósito
    -tfg tool        pequeñas utilidades para archivos que ya tienes
    -tfg version     imprimir la versión de la herramienta
    -tfg license     imprimir la licencia y qué significa para los archivos generados
    -

    - tfg tool reúne las herramientas para archivos que ya tienes, como comprobar un archivo - comprimido antes de descomprimirlo. Herramientas describe cada una. -

    -
    - -
    -

    ¿Cómo genero un único archivo de tamaño exacto?

    -

    - Indica el formato, el tamaño y dónde va. Los tamaños cuentan de 1024 en 1024, así que - 2mb son 2097152 bytes. Un número de bytes simple también sirve, de modo que - --size 10485761 pide exactamente esa cantidad. -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    Las opciones útiles de generate:

    -
    - - - - - - - - - - - - - - - - - -
    OpciónQué hace
    --format <id>formato de los archivos, por ejemplo txt
    --size <size>tamaño exacto de cada archivo, como 10mb o un número de bytes simple
    --size-range <a-b>un tamaño sacado por archivo de un intervalo, como 1kb-8kb. El sorteo viene de la semilla
    --boundary <size>tres archivos alrededor de un límite: un byte por debajo, el límite, un byte por encima
    --count <n>cuántos archivos producir. Por defecto 1
    --name <template>plantilla de nombre, por ejemplo invoice_{index:04}.txt
    --out <dir>directorio donde escribir
    --seed <n>semilla de la ejecución. La misma semilla da los mismos bytes
    --set <k>=<v>un ajuste de formato, repetible
    --damage <name>romper los archivos a propósito, repetible y aplicado en orden. Ejecuta tfg damage para ver la lista
    --expected <outcome>accept, reject, sanitize o unspecified
    --dry-runcontar y mostrar, sin escribir absolutamente nada
    --jsonescribir el manifiesto en la salida estándar
    -
    -
    - -
    -

    ¿Cómo hago un archivo roto a propósito?

    -

    - Todos los demás archivos que escribe esta herramienta son correctos por construcción, lo que - responde a dos de las tres preguntas que hace un validador de subidas. --damage - responde a la tercera - si el archivo se abre siquiera. El archivo se produce con normalidad y - luego se rompe, así que conserva el tamaño que pediste. -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - Los ajustes van después de dos puntos. La opción se repite, y el orden en que las escribes es el - orden en que se aplican. tfg damage lista lo que puede hacer esta versión y qué - admite cada una. -

    -

    En una receta la clave es una lista, de nombres o de ajustes:

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - Un archivo dañado recibe expected: reject en el manifiesto, con el daño registrado a su - lado. Dos cosas se rechazan antes de escribir nada, porque cada una dejaría en disco un archivo - que el manifiesto describe mal: -

    -
      -
    • un archivo más pequeño de lo que necesita el daño, porque saldría sin cambios
    • -
    • - expected: accept junto a un daño, porque nada podría cumplirlo. Escribe - sanitize si el sistema bajo prueba debe reparar el archivo, o - unspecified si esa es la pregunta que haces -
    • -
    -

    - Una tercera no se puede saber de antemano. Si un daño se ejecuta y no mueve ningún byte, ese archivo - se descarta en lugar de escribirse - la ejecución continúa, dice de qué archivo se trató y - termina con el código de salida parcial. -

    -

    - Paso a paso, con una prueba que lee el manifiesto: cómo - crear un archivo corrupto para pruebas. -

    -
    - -
    -

    ¿Qué aspecto tiene una receta?

    -

    - Una receta es un archivo YAML que describe una ejecución completa. Súbela al repositorio junto a tus - pruebas y los fixtures dejan de ser binarios en tu repositorio - cualquiera puede - reconstruirlos, byte a byte, a partir de un archivo de unos cientos de caracteres. -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - Cada target necesita exactamente una de estas claves: size, size-range, - boundary o contains. Dos es un error y ninguna también. Una receta - inválida escribe ningún archivo e informa de todos los problemas a la vez en - lugar de solo del primero, cada uno nombrando el ajuste al que se refiere. -

    -
    - -
    -

    ¿Cómo declaro qué debe hacer mi sistema con un archivo?

    -

    Forma corta cuando basta con el resultado, forma larga cuando importa el motivo:

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - Los resultados son accept, reject, sanitize y - unspecified. Los motivos son una lista cerrada para que un informe pueda - agruparlos: content_malformed, count_limit, - dimensions_limit, duplicate, encoding_invalid, - extension_rule, filename_invalid, filename_too_long, - filename_traversal, malware_signature, mime_mismatch, - nesting_depth, none, size_limit y size_zero. -

    -

    - Un motivo nombra la regla en juego, no el veredicto. Por eso el mismo motivo puede - estar bajo cualquiera de los dos resultados - un archivo un byte por debajo de un límite es - accept, y la regla de la que trata sigue siendo size_limit. -

    -
    - -
    -

    ¿Qué hay en el manifiesto?

    -

    - Se escribe junto a los archivos al final de cada ejecución, incluida una ejecución interrumpida. Una - entrada por archivo: -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "0.6.0-rc1" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - Se añade un recipe_hash cuando la ejecución viene de una receta, y preset - con overrides cuando viene de un preset, de modo que un manifiesto siempre se puede - rastrear hasta lo que lo produjo. -

    -

    - Cada entrada lleva también target_id, el id del target de la receta que produjo el - archivo, y summary.by_target cuenta los archivos a los que llegó cada target. Una - receta con varios targets se puede comprobar así target por target sin leer nombres de archivo. -

    -
    - -
    -

    ¿Qué es un preset?

    -

    - Un conjunto de archivos listo que responde a una pregunta de prueba habitual, para que no tengas que - diseñar el conjunto tú. Los presets son recetas normales por debajo, y eject - imprime la receta para que la edites desde ahí. Cada preset tiene una - página propia con lo que suele encontrar, qué hay en el conjunto y cada ajuste que admite. -

    +
    +

    Páginas de la documentación

    • -

      Vacío y mínimo

      -

      ¿Pasa un archivo válido y tan pequeño como permite el formato?

      -

      empty-and-minimal

      +

      Instalación EN

      +

      Descargar para Windows, macOS o Linux, comprobar el archivo o instalar con Docker, npm, pip o Go.

    • -
    • -

      Manejo de nombres de archivo

      -

      ¿Mi sistema guardará, mostrará y devolverá un nombre de archivo que no esperaba?

      -

      filename-handling

      +
    • +

      Primeros pasos EN

      +

      Un primer archivo de tamaño exacto, luego diez mil, comprobados, borrados y escritos como receta.

    • -
    • -

      Tamaños de imagen

      -

      ¿Acepta mi sistema imágenes en los tamaños que usan las pantallas y las plataformas?

      -

      picture-sizes

      +
    • +

      Comandos EN

      +

      Cada comando y cada opción con su valor por defecto, y todos los códigos de salida.

      +
    • +
    • +

      Escribir recetas EN

      +

      Cada clave de una receta, tamaños, nombres de archivo, reacciones esperadas, daños, archivos comprimidos y presets.

    • -

      Límites de tamaño

      -

      ¿Se aplica un límite de tamaño exactamente donde se declara?

      -

      size-boundaries

      +

      Galería de recetas EN

      +

      Recetas listas para descargar para subidas, importaciones, archivos comprimidos, correo, multimedia, CI y archivos en masa.

      +
    • +
    • +

      Manifiesto EN

      +

      Cada campo de manifest.json y cómo lo lee una prueba.

    • -

      Importación de tablas

      -

      ¿Sobrevive mi importación de tablas a lo que exportan las herramientas reales?

      -

      tabular-import

      +

      Ajustes de formato EN

      +

      Cada ajuste de cada formato, con los valores que acepta y su valor por defecto.

    • -

      Codificación de texto

      -

      ¿Sabe mi lector en qué codificación está un archivo, o lo adivina?

      -

      text-encoding

      +

      Frameworks de pruebas EN

      +

      Los archivos dentro de pytest, Playwright, Vitest y node:test.

      +
    • +
    • +

      Aplicación de escritorio EN

      +

      La ventana, pantalla por pantalla.

    • -

      Validación de subida

      -

      ¿Mi formulario de subida acepta lo que debe y rechaza el resto?

      -

      upload-validation

      +

      Herramientas

      +

      Herramientas sin conexión para tus archivos: ver si es seguro descomprimir un archivo comprimido (zip slip, zip bomb) y verificar o escribir sumas SHA-256.

    -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show te dice cuánto costaría el conjunto antes de construirlo, y dice sin rodeos cuándo - un número es un marcador nuestro en lugar de un límite tuyo. -

    -
    -

    ¿Qué significan los códigos de salida?

    -

    - Cada final tiene su propio código, la salida legible por máquina va a la salida estándar, y una - ejecución fallida no imprime nada allí. La tabla es un contrato congelado - cambiar lo que - significa un código exige una versión mayor. -

    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    CódigoSignificado
    0Todo ha funcionado.
    1Un error inesperado dentro de la herramienta.
    2Comando u opción incorrectos.
    3La receta no es válida.
    4El formato no puede hacer lo que se pidió.
    5Ha fallado una lectura o una escritura.
    6No hay espacio suficiente en disco.
    7verify ha encontrado una discrepancia.
    8La ejecución terminó, pero no se produjo todo.
    130Interrumpido con Ctrl+C.
    143Detenido por una señal, que es el aspecto de un tiempo de espera agotado en CI.
    -
    -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - Una ejecución detenida con Ctrl+C sigue dejando un manifiesto y nunca deja un archivo a medio - escribir, así que un trabajo cancelado aún puede limpiarlo el siguiente. -

    -

    - Workflows listos para GitHub Actions y GitLab CI: cómo - generar archivos de prueba en un pipeline de CI. -

    +
    +

    Qué hace la herramienta, tema por tema

    +
      +
    • +

      Formatos

      +

      Todos los formatos que genera, el archivo más pequeño posible de cada uno y los ajustes que admite. Los 32 se abren en el programa que les corresponde.

      +
    • +
    • +

      Presets

      +

      Conjuntos listos de archivos de prueba, cada uno responde a una pregunta: límites de subida, nombres, codificaciones, importación, archivos vacíos y validación.

      +
    • +
    • +

      Archivos corruptos

      +

      Un archivo roto a propósito, con el tamaño exacto que pides y un manifiesto que dice que tu sistema debe rechazarlo. Para probar validación de subidas y parsers.

      +
    • +
    • +

      Archivos de ejemplo

      +

      Archivos de prueba para descargar: uno de cada formato de 1 MB, PDF, Word y Excel corruptos, tablas CSV e imágenes de marcador de posición, con su SHA-256.

      +
    • +
    • +

      Casos de prueba de subida

      +

      Casos de prueba de subida de archivos: límite de tamaño, archivos vacíos o corruptos, tipo incorrecto, nombres raros y ZIP, cada uno con su archivo de prueba.

      +
    • +
    • +

      Archivos de prueba en CI

      +

      Genera archivos de prueba en el pipeline en vez de subir binarios: workflow de GitHub Actions, job de GitLab, códigos de salida y la trampa de PowerShell.

      +
    • +
    • +

      Tamaño exacto

      +

      fsutil, dd, truncate y mkfile, medidos cada uno en su sistema, y por qué un archivo así creado no es un PDF ni un PNG cuando una prueba necesita uno.

      +
    • +
    -
    -

    ¿Hay una ventana de escritorio?

    -

    - Sí, el mismo motor con una ventana encima, para las pruebas que no se automatizan. No es una versión - recortada: una prueba compara las dos interfaces capacidad por capacidad, y todo lo que solo una - de ellas puede hacer debe declararse y justificarse en lugar de divergir en silencio. -

    +
    +

    ¿Sigues atascado?

    - Las pantallas son un lote, presets, varios lotes a la vez y Acerca de. Muestra lo que costaría una - ejecución antes de escribir nada, informa del progreso mientras corre y se puede cancelar a - medias sin dejar un archivo a medio escribir. Todavía no abre un archivo de receta - por ahora - las recetas son cosa de la línea de comandos, y la ventana construye sus lotes en el formulario. + tfg <command> --help muestra en la terminal lo que acepta un comando. Cada rechazo nombra el ajuste al que se refiere, el motivo y un valor que funcionaría. Si algo no se comporta como dice una página, avísanos. Es un error de la página o del programa.

    diff --git a/web/public/es/herramientas/index.html b/web/public/es/herramientas/index.html index 8c351a07..28f3a216 100644 --- a/web/public/es/herramientas/index.html +++ b/web/public/es/herramientas/index.html @@ -151,6 +151,21 @@
    +

    Documentación

    Comprobar un archivo comprimido antes de descomprimirlo y verificar sumas de comprobación

    diff --git a/web/public/fr/documentation/index.html b/web/public/fr/documentation/index.html index bc448b5e..6001bc93 100644 --- a/web/public/fr/documentation/index.html +++ b/web/public/fr/documentation/index.html @@ -147,395 +147,93 @@

    Documentation

    - Tout ce que fait l'outil, rangé selon les questions avec lesquelles les gens arrivent vraiment. Le - README du dépôt est la référence complète et correspond toujours à - la version que vous avez téléchargée. + Comment installer tfg, créer vos premiers fichiers de test, et tout ce que le programme accepte et écrit : chaque commande et chaque option, chaque clé d'une recette, chaque champ du manifeste et chaque réglage de chaque format. Ces pages sont en anglais, car elles sont produites par le programme lui-même à chaque construction du site, et disent donc toujours ce que fait la version que vous téléchargez.

    -
    -

    Quelles commandes existe-t-il ?

    -

    Chacune fait une seule chose :

    -
    tfg generate    produire des fichiers, depuis une recette ou des options
    -tfg validate    vérifier une recette sans rien écrire
    -tfg verify      comparer un répertoire à un manifeste
    -tfg cleanup     supprimer les fichiers qu'un manifeste liste
    -tfg recipe fmt  afficher une recette sous sa forme normalisée
    -tfg preset      construire un jeu de fichiers à partir d'une question de test nommée
    -tfg formats     lister les formats pris en charge par cette version
    -tfg damage      lister les façons dont cette version peut abîmer un fichier exprès
    -tfg tool        de petits outils pour des fichiers que vous avez déjà
    -tfg version     afficher la version de l'outil
    -tfg license     afficher la licence et ce qu'elle implique pour les fichiers générés
    -

    - tfg tool regroupe les outils pour les fichiers que vous avez déjà, comme la - vérification d'une archive avant de la décompresser. Outils décrit chacun - d'eux. -

    -
    - -
    -

    Comment générer un seul fichier de taille exacte ?

    -

    - Nommez le format, la taille et la destination. Les tailles se comptent par 1024, donc - 2mb font 2097152 octets. Un nombre d'octets brut fonctionne aussi, donc - --size 10485761 demande exactement ce nombre. -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    Les options utiles de generate :

    -
    - - - - - - - - - - - - - - - - - -
    OptionCe qu'elle fait
    --format <id>format des fichiers, par exemple txt
    --size <size>taille exacte de chaque fichier, comme 10mb ou un nombre d'octets brut
    --size-range <a-b>une taille tirée par fichier dans une plage, comme 1kb-8kb. Le tirage vient de la graine
    --boundary <size>trois fichiers autour d'une limite : un octet en dessous, la limite, un octet au-dessus
    --count <n>combien de fichiers produire. Par défaut 1
    --name <template>modèle de nom, par exemple invoice_{index:04}.txt
    --out <dir>répertoire où écrire
    --seed <n>graine de l'exécution. La même graine donne les mêmes octets
    --set <k>=<v>un réglage de format, répétable
    --damage <name>abîmer les fichiers exprès, répétable et appliqué dans l'ordre. Lancez tfg damage pour la liste
    --expected <outcome>accept, reject, sanitize ou unspecified
    --dry-runcompter et montrer, sans rien écrire du tout
    --jsonécrire le manifeste sur la sortie standard
    -
    -
    - -
    -

    Comment fabriquer un fichier volontairement cassé ?

    -

    - Tout autre fichier écrit par cet outil est correct par construction, ce qui répond à deux des trois - questions que pose un validateur d'envoi. --damage répond à la troisième - le - fichier s'ouvre-t-il seulement. Le fichier est produit normalement puis abîmé, il garde donc la - taille demandée. -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - Les réglages se placent après deux-points. L'option se répète, et l'ordre dans lequel vous les - écrivez est l'ordre dans lequel ils sont appliqués. tfg damage liste ce que cette - version sait faire et ce que chacun accepte. -

    -

    Dans une recette, la clé est une liste, de noms ou de réglages :

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - Un fichier abîmé reçoit expected: reject dans le manifeste, avec l'altération notée à - côté. Deux choses sont refusées avant que rien ne soit écrit, car chacune mettrait sinon sur le - disque un fichier que le manifeste décrit à tort : -

    -
      -
    • un fichier plus petit que ce dont l'altération a besoin, car il ressortirait inchangé
    • -
    • - expected: accept à côté d'une altération, car rien ne pourrait y répondre. Écrivez - sanitize si le système testé doit réparer le fichier, ou unspecified - si c'est justement la question que vous posez -
    • -
    -

    - Une troisième ne peut pas être connue à l'avance. Si une altération s'exécute sans déplacer un seul - octet, ce fichier est abandonné plutôt qu'écrit - l'exécution continue, dit de quel fichier il - s'agissait et se termine avec le code de sortie partiel. -

    -

    - Pas à pas, avec un test qui lit le manifeste : - comment fabriquer un fichier corrompu pour les - tests. -

    -
    - -
    -

    À quoi ressemble une recette ?

    -

    - Une recette est un fichier YAML qui décrit toute une exécution. Commitez-la à côté de vos tests et - les fixtures cessent d'être des binaires dans votre dépôt - n'importe qui peut les reconstruire, - à l'octet près, à partir d'un fichier de quelques centaines de caractères. -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - Chaque cible exige exactement une de ces clés : size, size-range, - boundary ou contains. Deux est une erreur, et aucune aussi. Une - recette invalide n'écrit aucun fichier et signale tous les problèmes d'un coup - plutôt que le premier seulement, chacun nommant le réglage concerné. -

    -
    - -
    -

    Comment déclarer ce que mon système doit faire d'un fichier ?

    -

    Forme courte quand le résultat suffit, forme longue quand la raison compte :

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - Les résultats sont accept, reject, sanitize et - unspecified. Les raisons forment une liste fermée pour qu'un rapport puisse les - regrouper : content_malformed, count_limit, - dimensions_limit, duplicate, encoding_invalid, - extension_rule, filename_invalid, filename_too_long, - filename_traversal, malware_signature, mime_mismatch, - nesting_depth, none, size_limit et - size_zero. -

    -

    - Une raison nomme la règle en jeu, pas le verdict. C'est pourquoi la même raison - peut se trouver sous l'un ou l'autre résultat - un fichier un octet sous une limite est - accept, et la règle concernée reste size_limit. -

    -
    - -
    -

    Que contient le manifeste ?

    -

    - Il est écrit à côté des fichiers à la fin de chaque exécution, y compris d'une exécution - interrompue. Une entrée par fichier : -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "0.6.0-rc1" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - Un recipe_hash est ajouté quand l'exécution vient d'une recette, et preset - avec overrides quand elle vient d'un préréglage, de sorte qu'un manifeste peut - toujours être rattaché à ce qui l'a produit. -

    -

    - Chaque entrée porte aussi target_id, l'identifiant de la cible de la recette qui a - produit le fichier, et summary.by_target compte les fichiers de chaque cible. Une - recette à plusieurs cibles peut donc être vérifiée cible par cible sans lire les noms de - fichiers. -

    -
    - -
    -

    Qu'est-ce qu'un préréglage ?

    -

    - Un jeu de fichiers prêt à l'emploi qui répond à une question de test courante, pour que vous n'ayez - pas à concevoir le jeu vous-même. Les préréglages sont des recettes ordinaires en dessous, et - eject affiche la recette pour que vous puissiez la modifier. Chaque préréglage a - sa propre page qui dit ce qu'il trouve d'habitude, ce que - contient le jeu et chaque réglage qu'il accepte. -

    +
    +

    Pages de la documentation

    • -

      Vide et minimal

      -

      Un fichier valide et aussi petit que le format le permet passe-t-il ?

      -

      empty-and-minimal

      +

      Installation EN

      +

      Télécharger pour Windows, macOS ou Linux, vérifier l'archive, ou installer avec Docker, npm, pip ou Go.

    • -
    • -

      Gestion des noms de fichiers

      -

      Mon système va-t-il stocker, afficher et restituer un nom de fichier auquel il ne s'attendait pas ?

      -

      filename-handling

      +
    • +

      Premiers pas EN

      +

      Un premier fichier de taille exacte, puis dix mille, vérifiés, supprimés et décrits dans une recette.

    • -
    • -

      Tailles d'image

      -

      Mon système accepte-t-il les images aux tailles qu'utilisent les écrans et les plateformes ?

      -

      picture-sizes

      +
    • +

      Commandes EN

      +

      Chaque commande et chaque option avec sa valeur par défaut, et tous les codes de sortie.

      +
    • +
    • +

      Écrire une recette EN

      +

      Chaque clé d'une recette, les tailles, les noms de fichiers, les réactions attendues, les dommages, les archives et les presets.

    • -

      Limites de taille

      -

      Une limite de taille est-elle appliquée exactement là où elle est déclarée ?

      -

      size-boundaries

      +

      Galerie de recettes EN

      +

      Des recettes prêtes à télécharger pour les envois, les imports, les archives, les e-mails, les médias, la CI et les fichiers en masse.

      +
    • +
    • +

      Manifeste EN

      +

      Chaque champ de manifest.json, et comment un test le lit.

    • -

      Import de tableaux

      -

      Mon import de tableaux résiste-t-il à ce qu'exportent les vrais outils ?

      -

      tabular-import

      +

      Réglages des formats EN

      +

      Chaque réglage de chaque format, avec les valeurs acceptées et la valeur par défaut.

    • -

      Encodage du texte

      -

      Mon lecteur sait-il dans quel encodage est un fichier, ou devine-t-il ?

      -

      text-encoding

      +

      Frameworks de test EN

      +

      Les fichiers dans pytest, Playwright, Vitest et node:test.

      +
    • +
    • +

      Application de bureau EN

      +

      La fenêtre, écran par écran.

    • -

      Validation d'envoi

      -

      Mon formulaire d'envoi accepte-t-il ce qu'il doit et refuse-t-il le reste ?

      -

      upload-validation

      +

      Outils

      +

      Outils hors ligne pour vos fichiers : savoir si une archive se décompresse sans danger, zip slip et bombe zip compris, et vérifier ou écrire des sommes SHA-256.

    -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show vous dit ce que coûterait le jeu avant que vous ne le construisiez, et dit - franchement quand un nombre est un substitut de notre part plutôt qu'une limite de la vôtre. -

    -
    -

    Que signifient les codes de sortie ?

    -

    - Chaque fin a son propre code, la sortie lisible par machine va sur la sortie standard, et une - exécution échouée n'y écrit rien. Le tableau est un contrat figé - changer le sens d'un code - exige une version majeure. -

    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    CodeSignification
    0Tout a fonctionné.
    1Une erreur inattendue dans l'outil.
    2Commande ou option incorrecte.
    3La recette n'est pas valide.
    4Le format ne peut pas faire ce qui était demandé.
    5Une lecture ou une écriture a échoué.
    6Espace disque insuffisant.
    7verify a trouvé une différence.
    8L'exécution s'est terminée mais tout n'a pas été produit.
    130Interrompu avec Ctrl+C.
    143Arrêté par un signal, ce qui ressemble à un délai dépassé en CI.
    -
    -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - Une exécution arrêtée avec Ctrl+C laisse quand même un manifeste et ne laisse jamais de fichier à - moitié écrit, si bien qu'une tâche annulée peut encore être nettoyée par la suivante. -

    -

    - Des workflows prêts pour GitHub Actions et GitLab CI : - comment générer des fichiers de test dans un pipeline - CI. -

    +
    +

    Ce que fait l'outil, sujet par sujet

    +
      +
    • +

      Formats

      +

      Tous les formats générés, le plus petit fichier possible pour chacun et les réglages qu'il accepte. Les 32 s'ouvrent dans le logiciel qui leur correspond.

      +
    • +
    • +

      Préréglages

      +

      Jeux de fichiers de test prêts à l'emploi, un par question : limites d'envoi, noms de fichiers, encodages, import de tableaux, fichiers vides, validation d'envoi.

      +
    • +
    • +

      Fichiers corrompus

      +

      Un fichier cassé volontairement, à la taille exacte, avec un manifeste disant que votre système doit le rejeter. Pour tester la validation d'envoi et les parseurs.

      +
    • +
    • +

      Fichiers d'exemple

      +

      Fichiers de test et d'exemple à télécharger : chaque format à 1 Mo, PDF, Word et Excel corrompus, tableaux CSV et images de substitution, avec leur SHA-256.

      +
    • +
    • +

      Cas de test d'envoi

      +

      Cas de test d'envoi (upload) de fichiers : limite de taille, fichiers vides et corrompus, mauvais type, noms inattendus et archives, chacun avec son fichier.

      +
    • +
    • +

      Fichiers de test en CI

      +

      Générez des fichiers de test dans le pipeline plutôt que de commiter des binaires : workflow GitHub Actions, job GitLab, codes de sortie et piège PowerShell.

      +
    • +
    • +

      Taille exacte

      +

      fsutil, dd, truncate et mkfile, mesurés chacun sur son système, et pourquoi un fichier ainsi créé n'est ni un PDF ni un PNG quand un test en exige un.

      +
    • +
    -
    -

    Y a-t-il une fenêtre de bureau ?

    -

    - Oui, le même moteur avec une fenêtre, pour les tests qui ne sont pas scriptés. Ce n'est pas une - version amputée : un test compare les deux interfaces fonctionnalité par fonctionnalité, et - tout ce que seule l'une peut faire doit être déclaré et justifié au lieu de diverger - discrètement. -

    +
    +

    Toujours bloqué ?

    - Les écrans sont un lot, les préréglages, plusieurs lots à la fois et À propos. Elle montre ce que - coûterait une exécution avant d'écrire quoi que ce soit, indique la progression pendant - l'exécution et peut être annulée en cours de route sans laisser de fichier à moitié écrit. Elle - n'ouvre pas encore de fichier de recette - les recettes sont pour l'instant une affaire de ligne - de commande, et la fenêtre construit ses lots dans le formulaire. + tfg <command> --help indique dans le terminal ce qu'une commande accepte. Chaque refus nomme le réglage concerné, la raison et une valeur qui fonctionnerait. Si quelque chose ne se comporte pas comme une page le dit, signalez-le. C'est une erreur de la page ou du programme.

    diff --git a/web/public/fr/outils/index.html b/web/public/fr/outils/index.html index 3e1949c0..ecd283c4 100644 --- a/web/public/fr/outils/index.html +++ b/web/public/fr/outils/index.html @@ -151,6 +151,21 @@
    +

    Documentation

    Vérifier une archive avant de la décompresser, et contrôler les sommes

    diff --git a/web/public/hi/docs/index.html b/web/public/hi/docs/index.html index 27363cf9..17c76f58 100644 --- a/web/public/hi/docs/index.html +++ b/web/public/hi/docs/index.html @@ -147,385 +147,93 @@

    दस्तावेज़ीकरण

    - टूल जो कुछ भी करता है, उन सवालों के रूप में सजाया गया जिन्हें लेकर लोग सच में आते हैं। - रिपॉज़िटरी का README पूरा संदर्भ है और हमेशा आपके डाउनलोड किए - बिल्ड से मेल खाता है। + tfg कैसे इंस्टॉल करें, अपनी पहली टेस्ट फ़ाइलें कैसे बनाएँ, और वह सब कुछ जो प्रोग्राम लेता और लिखता है: हर कमांड और हर फ़्लैग, रेसिपी की हर कुंजी, मैनिफ़ेस्ट का हर फ़ील्ड और हर फ़ॉर्मैट की हर सेटिंग। ये पेज अंग्रेज़ी में हैं, क्योंकि साइट हर बार बनते समय ये प्रोग्राम से ही बनते हैं, इसलिए हमेशा वही बताते हैं जो आपका डाउनलोड किया संस्करण करता है।

    -
    -

    कौन सी कमांड हैं?

    -

    हर एक सिर्फ़ एक काम करती है:

    -
    tfg generate    रेसिपी या फ़्लैग से फ़ाइलें बनाएँ
    -tfg validate    रेसिपी जाँचें और कुछ न लिखें
    -tfg verify      किसी डायरेक्टरी को मैनिफ़ेस्ट से मिलाकर जाँचें
    -tfg cleanup     मैनिफ़ेस्ट में सूचीबद्ध फ़ाइलें हटाएँ
    -tfg recipe fmt  रेसिपी को उसके स्थिर रूप में छापें
    -tfg preset      किसी नामित टेस्ट सवाल से फ़ाइलों का सेट बनाएँ
    -tfg formats     इस बिल्ड के समर्थित फ़ॉर्मैट सूचीबद्ध करें
    -tfg damage      इस बिल्ड द्वारा किसी फ़ाइल को जानबूझकर बिगाड़ने के तरीके सूचीबद्ध करें
    -tfg tool        आपके पास पहले से मौजूद फ़ाइलों के लिए छोटे टूल
    -tfg version     टूल का संस्करण छापें
    -tfg license     लाइसेंस और बनाई गई फ़ाइलों के लिए उसका अर्थ छापें
    -

    - tfg tool में आपके पास पहले से मौजूद फ़ाइलों के लिए टूल हैं, जैसे किसी आर्काइव को - एक्सट्रैक्ट करने से पहले जाँचना। टूल पेज हर एक के बारे में बताता है। -

    -
    - -
    -

    सटीक आकार की एक फ़ाइल कैसे बनाऊँ?

    -

    - फ़ॉर्मैट, आकार और जगह बताएँ। आकार 1024 के गुणकों में गिने जाते हैं, इसलिए 2mb 2097152 - बाइट है। सादी बाइट संख्या भी चलती है, इसलिए --size 10485761 ठीक उतने ही बाइट माँगता - है। -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    generate के काम के फ़्लैग:

    -
    - - - - - - - - - - - - - - - - - -
    फ़्लैगक्या करता है
    --format <id>फ़ाइलों का फ़ॉर्मैट, जैसे txt
    --size <size>हर फ़ाइल का सटीक आकार, जैसे 10mb या सादी बाइट संख्या
    --size-range <a-b>किसी सीमा में से हर फ़ाइल के लिए निकाला गया आकार, जैसे 1kb-8kb। निकालना सीड से होता है
    --boundary <size>सीमा के आसपास तीन फ़ाइलें: एक बाइट नीचे, सीमा, एक बाइट ऊपर
    --count <n>कितनी फ़ाइलें बनानी हैं। डिफ़ॉल्ट 1
    --name <template>नाम का साँचा, जैसे invoice_{index:04}.txt
    --out <dir>जिस डायरेक्टरी में लिखना है
    --seed <n>रन का सीड। वही सीड वही बाइट देता है
    --set <k>=<v>फ़ॉर्मैट की एक सेटिंग, दोहराई जा सकती है
    --damage <name>फ़ाइलों को जानबूझकर बिगाड़ें, दोहराया जा सकता है और क्रम से लागू होता है। सूची के लिए tfg damage चलाएँ
    --expected <outcome>accept, reject, sanitize या unspecified
    --dry-runगिनें और दिखाएँ, कुछ भी न लिखें
    --jsonमैनिफ़ेस्ट को स्टैंडर्ड आउटपुट पर लिखें
    -
    -
    - -
    -

    जानबूझकर टूटी फ़ाइल कैसे बनाऊँ?

    -

    - यह टूल जो भी दूसरी फ़ाइल लिखता है वह बनावट से सही होती है, और इससे अपलोड वैलिडेटर के तीन सवालों में - से दो का जवाब मिल जाता है। --damage तीसरे का जवाब देता है - क्या फ़ाइल खुलती भी है। - फ़ाइल सामान्य रूप से बनती है और फिर बिगाड़ी जाती है, इसलिए उसका आकार वही रहता है जो आपने माँगा। -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - सेटिंग कोलन के बाद आती हैं। फ़्लैग दोहराया जा सकता है, और आप जिस क्रम में लिखते हैं वही उनके लागू - होने का क्रम है। tfg damage बताता है कि यह बिल्ड क्या कर सकता है और हर एक क्या लेता - है। -

    -

    रेसिपी में कुंजी एक सूची है, नामों की या सेटिंग की:

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - बिगाड़ी गई फ़ाइल को मैनिफ़ेस्ट में expected: reject मिलता है, और बिगाड़ने का ब्योरा - उसके बगल में दर्ज होता है। दो चीज़ें कुछ भी लिखे जाने से पहले ठुकरा दी जाती हैं, क्योंकि हर एक - डिस्क पर ऐसी फ़ाइल छोड़ देती जिसे मैनिफ़ेस्ट गलत बताता: -

    -
      -
    • बिगाड़ने के लिए ज़रूरी से छोटी फ़ाइल, क्योंकि वह बिना बदले निकल आती
    • -
    • - बिगाड़ के बगल में expected: accept, क्योंकि कुछ भी उसे पूरा नहीं कर सकता। अगर जाँचे जा - रहे सिस्टम को फ़ाइल सुधारनी है तो sanitize लिखें, या अगर आप यही सवाल पूछ रहे हैं - तो unspecified -
    • -
    -

    - तीसरी बात पहले से नहीं जानी जा सकती। अगर कोई बिगाड़ चलता है और एक भी बाइट नहीं हिलाता, तो वह फ़ाइल - लिखे जाने के बजाय छोड़ दी जाती है - रन चलता रहता है, बताता है कि वह कौन सी फ़ाइल थी, और आंशिक - एग्ज़िट कोड के साथ ख़त्म होता है। -

    -

    - कदम दर कदम, मैनिफ़ेस्ट पढ़ने वाले एक टेस्ट के साथ: परीक्षण के लिए - खराब फ़ाइल कैसे बनाएँ। -

    -
    - -
    -

    रेसिपी कैसी दिखती है?

    -

    - रेसिपी एक YAML फ़ाइल है जो पूरे रन का वर्णन करती है। इसे अपने टेस्ट के बगल में कमिट करें और - फ़िक्स्चर आपकी रिपॉज़िटरी में बाइनरी नहीं रह जाते - कोई भी उन्हें कुछ सौ अक्षरों की फ़ाइल से - बाइट-दर-बाइट दोबारा बना सकता है। -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - हर टार्गेट को size, size-range, boundary या - contains में से ठीक एक चाहिए। दो होना त्रुटि है और एक भी न होना भी। अमान्य रेसिपी - कोई फ़ाइल नहीं लिखती और सिर्फ़ पहली नहीं, सारी समस्याएँ एक साथ बताती है, हर एक - उस सेटिंग का नाम लेकर जिससे वह जुड़ी है। -

    -
    - -
    -

    मैं कैसे बताऊँ कि मेरे सिस्टम को किसी फ़ाइल के साथ क्या करना चाहिए?

    -

    जब नतीजा काफ़ी हो तो छोटा रूप, जब कारण मायने रखे तो लंबा रूप:

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - नतीजे हैं accept, reject, sanitize और - unspecified। कारण एक बंद सूची हैं ताकि रिपोर्ट उनके आधार पर समूह बना सके: - content_malformed, count_limit, dimensions_limit, - duplicate, encoding_invalid, extension_rule, - filename_invalid, filename_too_long, filename_traversal, - malware_signature, mime_mismatch, nesting_depth, - none, size_limit और size_zero। -

    -

    - कारण काम कर रहे नियम का नाम लेता है, फ़ैसले का नहीं। इसीलिए एक ही कारण किसी भी - नतीजे के नीचे आ सकता है - सीमा से एक बाइट नीचे की फ़ाइल accept है, और जिस नियम की - बात है वह फिर भी size_limit है। -

    -
    - -
    -

    मैनिफ़ेस्ट में क्या है?

    -

    - यह हर रन के अंत में फ़ाइलों के बगल में लिखा जाता है, बीच में रोके गए रन में भी। हर फ़ाइल के लिए एक - प्रविष्टि: -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "0.6.0-rc1" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - रन रेसिपी से आया हो तो recipe_hash जुड़ता है, और प्रीसेट से आया हो तो - overrides के साथ preset, इसलिए मैनिफ़ेस्ट को हमेशा उसके स्रोत तक खोजा - जा सकता है। -

    -

    - हर प्रविष्टि में target_id भी होता है, यानी रेसिपी के उस टार्गेट का id जिसने फ़ाइल - बनाई, और summary.by_target गिनता है कि हर टार्गेट के हिस्से कितनी फ़ाइलें आईं। - इसलिए कई टार्गेट वाली रेसिपी को फ़ाइल नाम पढ़े बिना टार्गेट-दर-टार्गेट जाँचा जा सकता है। -

    -
    - -
    -

    प्रीसेट क्या है?

    -

    - किसी आम टेस्ट सवाल का जवाब देने वाला फ़ाइलों का तैयार सेट, ताकि आपको सेट खुद डिज़ाइन न करना पड़े। - प्रीसेट अंदर से सामान्य रेसिपी हैं, और eject रेसिपी छापता है ताकि आप वहीं से उसे - संपादित कर सकें। हर प्रीसेट का अपना पेज है जो बताता है कि वह आम तौर - पर क्या पकड़ता है, सेट में क्या है और वह कौन सी सेटिंग लेता है। -

    +
    +

    दस्तावेज़ीकरण के पेज

    • -

      खाली और न्यूनतम

      -

      क्या फ़ॉर्मैट की अनुमति जितनी छोटी वैध फ़ाइल पास हो जाती है?

      -

      empty-and-minimal

      +

      इंस्टॉल करना EN

      +

      Windows, macOS या Linux के लिए डाउनलोड करें, आर्काइव जाँचें, या Docker, npm, pip या Go से इंस्टॉल करें।

    • -
    • -

      फ़ाइल नाम का प्रबंधन

      -

      क्या मेरा सिस्टम ऐसा फ़ाइल नाम सहेजेगा, दिखाएगा और लौटाएगा जिसकी उसे उम्मीद नहीं थी?

      -

      filename-handling

      +
    • +

      शुरुआत EN

      +

      सटीक आकार की पहली फ़ाइल, फिर दस हज़ार, जाँची गईं, हटाई गईं और रेसिपी के रूप में लिखी गईं।

    • -
    • -

      तस्वीरों के आकार

      -

      क्या मेरा सिस्टम उन आकारों की तस्वीरें लेता है जो स्क्रीन और प्लेटफ़ॉर्म इस्तेमाल करते हैं?

      -

      picture-sizes

      +
    • +

      कमांड EN

      +

      हर कमांड और हर फ़्लैग अपने डिफ़ॉल्ट मान के साथ, और सभी एग्ज़िट कोड।

      +
    • +
    • +

      रेसिपी लिखना EN

      +

      रेसिपी की हर कुंजी, आकार, फ़ाइल नाम, अपेक्षित प्रतिक्रियाएँ, क्षति, आर्काइव और प्रीसेट।

    • -

      आकार की सीमाएँ

      -

      क्या आकार की सीमा ठीक वहीं लागू होती है जहाँ उसकी घोषणा की गई है?

      -

      size-boundaries

      +

      रेसिपी संग्रह EN

      +

      अपलोड, इंपोर्ट, आर्काइव, ईमेल, मीडिया, CI और बड़ी संख्या की फ़ाइलों के लिए डाउनलोड करने को तैयार रेसिपी।

      +
    • +
    • +

      मैनिफ़ेस्ट EN

      +

      manifest.json का हर फ़ील्ड और टेस्ट उसे कैसे पढ़ता है।

    • -

      टेबल इंपोर्ट

      -

      क्या मेरा टेबल इंपोर्ट वह झेल पाता है जो असली टूल एक्सपोर्ट करते हैं?

      -

      tabular-import

      +

      फ़ॉर्मैट सेटिंग EN

      +

      हर फ़ॉर्मैट की हर सेटिंग, स्वीकार्य मानों और डिफ़ॉल्ट मान के साथ।

    • -

      टेक्स्ट एन्कोडिंग

      -

      क्या मेरा रीडर जानता है कि फ़ाइल किस एन्कोडिंग में है, या अंदाज़ा लगा रहा है?

      -

      text-encoding

      +

      टेस्ट फ़्रेमवर्क EN

      +

      pytest, Playwright, Vitest और node:test के अंदर फ़ाइलें।

      +
    • +
    • +

      डेस्कटॉप ऐप EN

      +

      प्रोग्राम की विंडो, एक-एक स्क्रीन करके।

    • -

      अपलोड सत्यापन

      -

      क्या मेरा अपलोड फ़ॉर्म वह लेता है जो उसे लेना चाहिए और बाकी को लौटा देता है?

      -

      upload-validation

      +

      टूल

      +

      आपके पास मौजूद फ़ाइलों के लिए ऑफ़लाइन टूल: देखें कि आर्काइव को एक्सट्रैक्ट करना सुरक्षित है या नहीं, zip slip और zip bomb समेत, और SHA-256 चेकसम जाँचें या लिखें।

    -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show सेट बनाने से पहले बताता है कि उसकी क़ीमत क्या होगी, और साफ़ कहता है जब कोई संख्या - आपकी सीमा नहीं बल्कि हमारी अस्थायी जगह-धारक संख्या हो। -

    -
    -

    एग्ज़िट कोड का क्या अर्थ है?

    -

    - हर अंत का अपना कोड है, मशीन के पढ़ने लायक आउटपुट स्टैंडर्ड आउटपुट पर जाता है, और विफल रन वहाँ कुछ - नहीं छापता। तालिका एक जमाया हुआ अनुबंध है - किसी कोड का अर्थ बदलने के लिए मुख्य संस्करण बढ़ाना - पड़ता है। -

    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    कोडअर्थ
    0सब कुछ ठीक चला।
    1टूल के अंदर एक अप्रत्याशित त्रुटि।
    2गलत कमांड या फ़्लैग।
    3रेसिपी मान्य नहीं है।
    4फ़ॉर्मैट वह नहीं कर सकता जो माँगा गया।
    5पढ़ना या लिखना विफल रहा।
    6डिस्क पर पर्याप्त जगह नहीं है।
    7verify को असंगति मिली।
    8रन पूरा हुआ, पर सब कुछ नहीं बना।
    130Ctrl+C से रोका गया।
    143एक सिग्नल से रोका गया, CI का टाइमआउट ऐसा ही दिखता है।
    -
    -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - Ctrl+C से रोका गया रन फिर भी मैनिफ़ेस्ट छोड़ता है और कभी आधी लिखी फ़ाइल नहीं छोड़ता, इसलिए रद्द किए - गए जॉब को अगला जॉब साफ़ कर सकता है। -

    -

    - GitHub Actions और GitLab CI के लिए तैयार वर्कफ़्लो: CI पाइपलाइन में - टेस्ट फ़ाइलें कैसे बनाएँ। -

    +
    +

    टूल क्या करता है, विषय के अनुसार

    +
      +
    • +

      फ़ॉर्मैट

      +

      जनरेटर के सभी फ़ाइल फ़ॉर्मैट, हर फ़ॉर्मैट की सबसे छोटी संभव फ़ाइल, और उनकी सेटिंग। सभी 32 अपने सॉफ़्टवेयर में खुलते हैं।

      +
    • +
    • +

      प्रीसेट

      +

      टेस्ट फ़ाइलों के तैयार सेट, हर सेट एक सवाल का जवाब देता है: अपलोड सीमा, फ़ाइल नाम, एन्कोडिंग, टेबल इंपोर्ट, खाली फ़ाइलें और अपलोड सत्यापन।

      +
    • +
    • +

      खराब फ़ाइलें

      +

      जानबूझकर बिगाड़ी गई, सटीक आकार की फ़ाइल, साथ में ऐसा मैनिफ़ेस्ट जो कहता है कि सिस्टम को उसे अस्वीकार करना चाहिए। अपलोड वैलिडेशन और पार्सर परखने के लिए।

      +
    • +
    • +

      सैंपल फ़ाइलें

      +

      टेस्टिंग के लिए सैंपल फ़ाइलें डाउनलोड करें: हर फ़ॉर्मैट की 1 MB की एक फ़ाइल, खराब PDF, Word और Excel फ़ाइलें, CSV टेबल और प्लेसहोल्डर तस्वीरें, हर एक के SHA-256 के साथ।

      +
    • +
    • +

      अपलोड टेस्ट केस

      +

      फ़ाइल अपलोड के टेस्ट केस: आकार सीमा, खाली और खराब फ़ाइलें, गलत प्रकार, अनपेक्षित फ़ाइल नाम और आर्काइव, हर केस के साथ वह फ़ाइल जो उसे परखती है।

      +
    • +
    • +

      CI में टेस्ट फ़ाइलें

      +

      बाइनरी कमिट करने के बजाय पाइपलाइन में टेस्ट फ़ाइलें बनाएँ: GitHub Actions वर्कफ़्लो, GitLab जॉब, एग्ज़िट कोड और PowerShell का जाल।

      +
    • +
    • +

      सटीक आकार

      +

      fsutil, dd, truncate और mkfile, हर एक अपने सिस्टम पर मापा गया, और जब टेस्ट को PDF या PNG चाहिए तब इस तरह बनी फ़ाइल क्यों काम नहीं आती।

      +
    • +
    -
    -

    क्या डेस्कटॉप विंडो है?

    -

    - हाँ, वही इंजन जिस पर एक विंडो लगी है, उस टेस्टिंग के लिए जो स्क्रिप्ट से नहीं होती। यह घटाया हुआ रूप - नहीं है: एक टेस्ट दोनों इंटरफ़ेस की क्षमता-दर-क्षमता तुलना करता है, और जो सिर्फ़ एक ही कर सकता - है उसे चुपचाप अलग होने देने के बजाय घोषित और उचित ठहराना पड़ता है। -

    +
    +

    अब भी अटके हैं?

    - स्क्रीन हैं एक बैच, प्रीसेट, एक साथ कई बैच, और परिचय। यह कुछ भी लिखने से पहले रन की क़ीमत दिखाती है, - चलते समय प्रगति बताती है, और बीच में रद्द की जा सकती है बिना आधी लिखी फ़ाइल छोड़े। यह अभी रेसिपी - फ़ाइल नहीं खोलती - फ़िलहाल रेसिपी कमांड लाइन की चीज़ हैं, और विंडो अपने बैच फ़ॉर्म में बनाती है। + tfg <command> --help टर्मिनल में बताता है कि कोई कमांड क्या लेता है। हर अस्वीकृति बताती है कि बात किस सेटिंग की है, कारण क्या है और कौन-सा मान चलेगा। अगर कुछ वैसा व्यवहार नहीं करता जैसा यहाँ कोई पेज कहता है, तो हमें बताएँ। वह पेज या प्रोग्राम की गलती है।

    diff --git a/web/public/hi/tools/index.html b/web/public/hi/tools/index.html index eade71f7..af7d0608 100644 --- a/web/public/hi/tools/index.html +++ b/web/public/hi/tools/index.html @@ -151,6 +151,21 @@
    +

    दस्तावेज़ीकरण

    एक्सट्रैक्ट करने से पहले आर्काइव जाँचें, और चेकसम सत्यापित करें

    diff --git a/web/public/id/alat/index.html b/web/public/id/alat/index.html index 8b199648..2522d647 100644 --- a/web/public/id/alat/index.html +++ b/web/public/id/alat/index.html @@ -151,6 +151,21 @@

    +

    Dokumentasi

    Periksa arsip sebelum diekstrak, dan verifikasi checksum

    diff --git a/web/public/id/dokumentasi/index.html b/web/public/id/dokumentasi/index.html index 2fd0de3c..2eb9ccda 100644 --- a/web/public/id/dokumentasi/index.html +++ b/web/public/id/dokumentasi/index.html @@ -147,390 +147,93 @@

    Dokumentasi

    - Semua yang dilakukan alat ini, disusun sebagai pertanyaan yang benar-benar dibawa orang. - README di repositori adalah referensi lengkap dan selalu sesuai - dengan build yang Anda unduh. + Cara memasang tfg, membuat berkas uji pertama Anda, dan semua yang diterima dan ditulis program: setiap perintah dan setiap opsi, setiap kunci resep, setiap bidang manifes, dan setiap pengaturan setiap format. Halaman-halaman ini berbahasa Inggris, karena dibuat dari program itu sendiri setiap kali situs dibangun, sehingga selalu sesuai dengan versi yang Anda unduh.

    -
    -

    Perintah apa saja yang ada?

    -

    Masing-masing melakukan satu hal:

    -
    tfg generate    menghasilkan file, dari resep atau dari opsi
    -tfg validate    memeriksa resep tanpa menulis apa pun
    -tfg verify      memeriksa direktori terhadap manifes
    -tfg cleanup     menghapus file yang tercantum dalam manifes
    -tfg recipe fmt  mencetak resep dalam bentuk bakunya
    -tfg preset      membuat set file dari pertanyaan pengujian bernama
    -tfg formats     mendaftar format yang didukung build ini
    -tfg damage      mendaftar cara build ini dapat merusak file dengan sengaja
    -tfg tool        alat kecil untuk file yang sudah Anda miliki
    -tfg version     mencetak versi alat
    -tfg license     mencetak lisensi dan artinya bagi file yang dihasilkan
    -

    - tfg tool berisi alat untuk file yang sudah Anda miliki, misalnya memeriksa arsip - sebelum diekstrak. Alat menjelaskan masing-masing. -

    -
    - -
    -

    Bagaimana cara membuat satu file dengan ukuran tepat?

    -

    - Sebutkan format, ukuran, dan tujuannya. Ukuran dihitung dalam kelipatan 1024, jadi 2mb - adalah 2097152 byte. Jumlah byte biasa juga bisa, jadi --size 10485761 meminta - persis sebanyak itu. -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    Opsi yang berguna pada generate:

    -
    - - - - - - - - - - - - - - - - - -
    OpsiFungsinya
    --format <id>format file, misalnya txt
    --size <size>ukuran tepat setiap file, seperti 10mb atau jumlah byte biasa
    --size-range <a-b>ukuran yang diundi per file dari suatu rentang, seperti 1kb-8kb. Undiannya berasal dari seed
    --boundary <size>tiga file di sekitar batas: satu byte di bawah, batas itu sendiri, satu byte di atas
    --count <n>berapa banyak file yang dibuat. Bawaan 1
    --name <template>templat nama, misalnya invoice_{index:04}.txt
    --out <dir>direktori tujuan penulisan
    --seed <n>seed run. Seed yang sama menghasilkan byte yang sama
    --set <k>=<v>pengaturan format, dapat diulang
    --damage <name>merusak file dengan sengaja, dapat diulang dan diterapkan berurutan. Jalankan tfg damage untuk daftarnya
    --expected <outcome>accept, reject, sanitize, atau unspecified
    --dry-runmenghitung dan menampilkan, tidak menulis apa pun
    --jsonmenulis manifes ke keluaran standar
    -
    -
    - -
    -

    Bagaimana membuat file yang sengaja dirusak?

    -

    - Setiap file lain yang ditulis alat ini benar menurut konstruksinya, yang menjawab dua dari tiga - pertanyaan yang diajukan validator unggahan. --damage menjawab yang ketiga - apakah - file itu dapat dibuka sama sekali. File dibuat secara normal lalu dirusak, sehingga ukurannya - tetap seperti yang Anda minta. -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - Pengaturan ditulis setelah titik dua. Opsinya dapat diulang, dan urutan penulisannya adalah urutan - penerapannya. tfg damage mendaftar apa yang bisa dilakukan build ini dan apa yang - diterima masing-masing. -

    -

    Dalam resep, kuncinya adalah daftar, berisi nama atau pengaturan:

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - File yang dirusak mendapat expected: reject di manifes, dengan kerusakan dicatat di - sampingnya. Dua hal ditolak sebelum apa pun ditulis, karena masing-masing akan menaruh file di - disk yang digambarkan manifes secara keliru: -

    -
      -
    • file yang lebih kecil dari yang dibutuhkan kerusakan, karena akan keluar tanpa perubahan
    • -
    • - expected: accept di samping kerusakan, karena tidak ada yang dapat memenuhinya. Tulis - sanitize bila sistem yang diuji dimaksudkan memperbaiki file, atau - unspecified bila itulah pertanyaan yang Anda ajukan -
    • -
    -

    - Yang ketiga tidak dapat diketahui sebelumnya. Bila suatu kerusakan berjalan dan tidak menggeser satu - byte pun, file itu dibuang alih-alih ditulis - run berlanjut, menyebut file mana itu, dan - berakhir dengan kode keluar parsial. -

    -

    - Langkah demi langkah, dengan tes yang membaca manifes: cara membuat - file rusak untuk pengujian. -

    -
    - -
    -

    Seperti apa bentuk sebuah resep?

    -

    - Resep adalah file YAML yang menggambarkan satu run utuh. Commit di samping pengujian Anda dan - fixture berhenti menjadi biner di repositori Anda - siapa pun dapat membangunnya kembali, byte - demi byte, dari file berisi beberapa ratus karakter. -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - Setiap target memerlukan tepat satu dari size, size-range, - boundary, atau contains. Dua adalah galat dan tidak ada juga galat. - Resep yang tidak valid menulis tidak ada file sama sekali dan melaporkan semua - masalah sekaligus, bukan hanya yang pertama, masing-masing menyebut pengaturan yang dimaksud. -

    -
    - -
    -

    Bagaimana menyatakan apa yang harus dilakukan sistem saya terhadap sebuah file?

    -

    Bentuk pendek bila hasilnya sudah cukup, bentuk panjang bila alasannya penting:

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - Hasilnya adalah accept, reject, sanitize, dan - unspecified. Alasannya adalah daftar tertutup agar laporan dapat mengelompokkan - berdasarkan itu: content_malformed, count_limit, - dimensions_limit, duplicate, encoding_invalid, - extension_rule, filename_invalid, filename_too_long, - filename_traversal, malware_signature, mime_mismatch, - nesting_depth, none, size_limit, dan - size_zero. -

    -

    - Alasan menyebut aturan yang berlaku, bukan putusannya. Itulah sebabnya alasan yang - sama dapat berada di bawah kedua hasil - file satu byte di bawah batas adalah - accept, dan aturan yang dimaksud tetap size_limit. -

    -
    - -
    -

    Apa isi manifes?

    -

    - Manifes ditulis di samping file pada akhir setiap run, termasuk run yang terhenti. Satu entri per - file: -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "0.6.0-rc1" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - recipe_hash ditambahkan bila run berasal dari resep, dan preset dengan - overrides bila berasal dari preset, sehingga manifes selalu dapat ditelusuri ke apa - yang menghasilkannya. -

    -

    - Setiap entri juga membawa target_id, id target dalam resep yang menghasilkan file, dan - summary.by_target menghitung file yang dihasilkan tiap target. Resep dengan - beberapa target dapat diperiksa target demi target tanpa membaca nama file. -

    -
    - -
    -

    Apa itu preset?

    -

    - Set file siap pakai yang menjawab pertanyaan pengujian umum, sehingga Anda tidak perlu merancang - setnya sendiri. Preset pada dasarnya resep biasa, dan eject mencetak resepnya agar - dapat Anda sunting dari sana. Setiap preset memiliki halamannya - sendiri berisi apa yang biasanya ditemukan, isi set, dan setiap pengaturan yang diterimanya. -

    +
    +

    Halaman dokumentasi

    • -

      Kosong dan minimal

      -

      Apakah file valid yang sekecil yang diizinkan format dapat lolos?

      -

      empty-and-minimal

      +

      Pemasangan EN

      +

      Unduh untuk Windows, macOS, atau Linux, periksa arsipnya, atau pasang dengan Docker, npm, pip, atau Go.

    • -
    • -

      Penanganan nama file

      -

      Apakah sistem saya akan menyimpan, menampilkan, dan mengembalikan nama file yang tidak diduganya?

      -

      filename-handling

      +
    • +

      Memulai EN

      +

      Berkas pertama dengan ukuran tepat, lalu sepuluh ribu, diperiksa, dihapus, dan ditulis sebagai resep.

    • -
    • -

      Ukuran gambar

      -

      Apakah sistem saya menerima gambar dalam ukuran yang dipakai layar dan platform?

      -

      picture-sizes

      +
    • +

      Perintah EN

      +

      Setiap perintah dan setiap opsi beserta nilai bawaannya, dan semua kode keluar.

      +
    • +
    • +

      Menulis resep EN

      +

      Setiap kunci resep, ukuran, nama berkas, reaksi yang diharapkan, kerusakan, arsip, dan preset.

    • -

      Batas ukuran

      -

      Apakah batas ukuran ditegakkan tepat di tempat batas itu dinyatakan?

      -

      size-boundaries

      +

      Galeri resep EN

      +

      Resep siap unduh untuk unggahan, impor, arsip, email, media, CI, dan berkas massal.

      +
    • +
    • +

      Manifes EN

      +

      Setiap bidang manifest.json dan cara tes membacanya.

    • -

      Impor tabel

      -

      Apakah impor tabel saya tahan terhadap apa yang diekspor alat sungguhan?

      -

      tabular-import

      +

      Pengaturan format EN

      +

      Setiap pengaturan setiap format, dengan nilai yang diterima dan nilai bawaannya.

    • -

      Enkoding teks

      -

      Apakah pembaca saya tahu enkoding suatu file, atau hanya menebak?

      -

      text-encoding

      +

      Framework pengujian EN

      +

      Berkas di dalam pytest, Playwright, Vitest, dan node:test.

      +
    • +
    • +

      Aplikasi desktop EN

      +

      Jendela program, layar demi layar.

    • -

      Validasi unggahan

      -

      Apakah formulir unggah saya menerima yang seharusnya dan menolak sisanya?

      -

      upload-validation

      +

      Alat

      +

      Alat offline untuk file yang sudah Anda miliki: periksa apakah arsip aman diekstrak, termasuk zip slip dan zip bomb, serta periksa atau tulis checksum SHA-256.

    -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show memberi tahu berapa biaya set sebelum Anda membuatnya, dan menyatakan terus terang - bila sebuah angka adalah nilai sementara dari kami, bukan batas dari Anda. -

    -
    -

    Apa arti kode keluar?

    -

    - Setiap akhir punya kodenya sendiri, keluaran yang terbaca mesin masuk ke keluaran standar, dan run - yang gagal tidak mencetak apa pun di sana. Tabelnya adalah kontrak beku - mengubah arti sebuah - kode memerlukan kenaikan versi mayor. -

    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    KodeArti
    0Semuanya berjalan.
    1Kesalahan tak terduga di dalam alat.
    2Perintah atau opsi salah.
    3Resep tidak valid.
    4Format tidak dapat melakukan yang diminta.
    5Pembacaan atau penulisan gagal.
    6Ruang disk tidak cukup.
    7verify menemukan ketidakcocokan.
    8Run selesai tetapi tidak semuanya dihasilkan.
    130Dihentikan dengan Ctrl+C.
    143Dihentikan oleh sinyal, seperti tampilan batas waktu CI.
    -
    -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - Run yang dihentikan dengan Ctrl+C tetap meninggalkan manifes dan tidak pernah meninggalkan file yang - tertulis setengah, sehingga job yang dibatalkan masih dapat dibersihkan oleh yang berikutnya. -

    -

    - Workflow siap pakai untuk GitHub Actions dan GitLab CI: cara membuat - file uji di pipeline CI. -

    +
    +

    Apa yang dilakukan alat ini, per topik

    +
      +
    • +

      Format

      +

      Semua format file yang dihasilkan, file terkecil yang mungkin untuk tiap format, dan pengaturan yang diterimanya. Semua 32 terbuka di aplikasi aslinya.

      +
    • +
    • +

      Preset

      +

      Set file uji siap pakai, masing-masing menjawab satu pertanyaan pengujian: batas unggahan, nama file, enkoding, impor tabel, file kosong, dan validasi.

      +
    • +
    • +

      File rusak

      +

      File yang sengaja dirusak, berukuran tepat, dengan manifes yang menyatakan sistem Anda harus menolaknya. Untuk menguji validasi unggahan dan parser.

      +
    • +
    • +

      Contoh file

      +

      Unduh contoh file untuk pengujian: satu file 1 MB per format, PDF, Word, dan Excel yang rusak, tabel CSV, dan gambar placeholder, masing-masing dengan SHA-256.

      +
    • +
    • +

      Kasus uji unggah

      +

      Kasus uji untuk unggah file: batas ukuran, file kosong dan rusak, tipe yang salah, nama file tak terduga, dan arsip, masing-masing dengan file yang mengujinya.

      +
    • +
    • +

      File uji di CI

      +

      Buat file uji di pipeline alih-alih meng-commit biner: workflow GitHub Actions, job GitLab, kode keluar, dan jebakan PowerShell.

      +
    • +
    • +

      Ukuran Tepat

      +

      fsutil, dd, truncate, dan mkfile, masing-masing diukur di sistemnya, dan mengapa file yang dibuat begitu bukan PDF atau PNG saat pengujian membutuhkannya.

      +
    • +
    -
    -

    Apakah ada jendela desktop?

    -

    - Ada, mesin yang sama dengan jendela di atasnya, untuk pengujian yang tidak diskripkan. Ini bukan - versi terpangkas: sebuah pengujian membandingkan kedua antarmuka kemampuan demi kemampuan, dan - apa pun yang hanya dapat dilakukan salah satunya harus dinyatakan dan dibenarkan alih-alih - diam-diam menyimpang. -

    +
    +

    Masih buntu?

    - Layarnya adalah satu batch, preset, beberapa batch sekaligus, dan tentang. Jendela ini menunjukkan - biaya sebuah run sebelum menulis apa pun, melaporkan kemajuan selama berjalan, dan dapat - dibatalkan di tengah jalan tanpa meninggalkan file yang tertulis setengah. Jendela ini belum - membuka file resep - untuk saat ini resep urusan baris perintah, dan jendela membangun batch-nya - di formulir. + tfg <command> --help menunjukkan di terminal apa yang diterima sebuah perintah. Setiap penolakan menyebut pengaturan yang dimaksud, alasannya, dan nilai yang akan berhasil. Jika sesuatu tidak berperilaku seperti yang dikatakan halaman ini, laporkan. Itu kesalahan halaman atau program.

    diff --git a/web/public/it/documentazione/index.html b/web/public/it/documentazione/index.html index b4d542ab..58e9fc55 100644 --- a/web/public/it/documentazione/index.html +++ b/web/public/it/documentazione/index.html @@ -147,388 +147,93 @@

    Documentazione

    - Tutto ciò che fa lo strumento, organizzato come le domande con cui le persone arrivano davvero. Il - README nel repository è il riferimento completo e corrisponde - sempre alla build che hai scaricato. + Come installare tfg, creare i primi file di test e tutto ciò che il programma accetta e scrive: ogni comando e ogni opzione, ogni chiave di una ricetta, ogni campo del manifest e ogni impostazione di ogni formato. Queste pagine sono in inglese, perché vengono prodotte dal programma stesso a ogni costruzione del sito, e dicono quindi sempre ciò che fa la versione che scarichi.

    -
    -

    Quali comandi esistono?

    -

    Ognuno fa una cosa sola:

    -
    tfg generate    produrre file, da una ricetta o da opzioni
    -tfg validate    controllare una ricetta senza scrivere nulla
    -tfg verify      controllare una directory rispetto a un manifest
    -tfg cleanup     rimuovere i file elencati da un manifest
    -tfg recipe fmt  stampare una ricetta nella sua forma normalizzata
    -tfg preset      costruire un set di file a partire da una domanda di test con nome
    -tfg formats     elencare i formati supportati da questa versione
    -tfg damage      elencare i modi in cui questa versione può rompere un file di proposito
    -tfg tool        piccole utilità per file che hai già
    -tfg version     stampare la versione dello strumento
    -tfg license     stampare la licenza e cosa significa per i file generati
    -

    - tfg tool raccoglie gli strumenti per i file che hai già, come il controllo di un archivio - prima di decomprimerlo. Strumenti descrive ciascuno di essi. -

    -
    - -
    -

    Come genero un singolo file di dimensione esatta?

    -

    - Indica il formato, la dimensione e la destinazione. Le dimensioni si contano a 1024, quindi - 2mb sono 2097152 byte. Funziona anche un semplice numero di byte, quindi - --size 10485761 chiede esattamente quel numero. -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    Le opzioni utili di generate:

    -
    - - - - - - - - - - - - - - - - - -
    OpzioneCosa fa
    --format <id>formato dei file, per esempio txt
    --size <size>dimensione esatta di ogni file, come 10mb o un semplice numero di byte
    --size-range <a-b>una dimensione estratta per file da un intervallo, come 1kb-8kb. L'estrazione viene dal seed
    --boundary <size>tre file attorno a un limite: un byte sotto, il limite, un byte sopra
    --count <n>quanti file produrre. Predefinito 1
    --name <template>modello del nome, per esempio invoice_{index:04}.txt
    --out <dir>directory in cui scrivere
    --seed <n>seed dell'esecuzione. Lo stesso seed dà gli stessi byte
    --set <k>=<v>un'impostazione di formato, ripetibile
    --damage <name>rompere i file di proposito, ripetibile e applicato in ordine. Esegui tfg damage per l'elenco
    --expected <outcome>accept, reject, sanitize oppure unspecified
    --dry-runcontare e mostrare, senza scrivere assolutamente nulla
    --jsonscrivere il manifest sullo standard output
    -
    -
    - -
    -

    Come faccio un file rotto di proposito?

    -

    - Ogni altro file che questo strumento scrive è corretto per costruzione, il che risponde a due delle - tre domande che pone un validatore di upload. --damage risponde alla terza - il - file si apre, almeno. Il file viene prodotto normalmente e poi rotto, quindi ha ancora la - dimensione che hai chiesto. -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - Le impostazioni vanno dopo i due punti. L'opzione si ripete, e l'ordine in cui le scrivi è l'ordine - in cui vengono applicate. tfg damage elenca cosa può fare questa versione e cosa - accetta ciascuno. -

    -

    In una ricetta la chiave è un elenco, di nomi o di impostazioni:

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - Un file danneggiato riceve expected: reject nel manifest, con il danno registrato - accanto. Due cose vengono rifiutate prima di scrivere qualsiasi cosa, perché ciascuna metterebbe - su disco un file che il manifest descrive in modo sbagliato: -

    -
      -
    • un file più piccolo di quanto serve al danno, perché uscirebbe invariato
    • -
    • - expected: accept accanto a un danno, perché nulla potrebbe soddisfarlo. Scrivi - sanitize se il sistema sotto test deve riparare il file, oppure - unspecified se è proprio la domanda che stai ponendo -
    • -
    -

    - Una terza non si può sapere in anticipo. Se un danno viene eseguito e non sposta alcun byte, quel - file viene scartato invece di essere scritto - l'esecuzione prosegue, dice di quale file si - trattava e termina con il codice di uscita parziale. -

    -

    - Passo dopo passo, con un test che legge il manifest: come - creare un file corrotto per i test. -

    -
    - -
    -

    Che aspetto ha una ricetta?

    -

    - Una ricetta è un file YAML che descrive un'intera esecuzione. Committala accanto ai tuoi test e le - fixture smettono di essere binari nel tuo repository - chiunque può ricostruirle, byte per byte, - da un file di poche centinaia di caratteri. -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - Ogni target richiede esattamente una di queste chiavi: size, size-range, - boundary o contains. Due è un errore, e anche nessuna. Una ricetta non - valida scrive nessun file e segnala tutti i problemi insieme invece del solo - primo, ognuno con il nome dell'impostazione a cui si riferisce. -

    -
    - -
    -

    Come dichiaro cosa deve fare il mio sistema con un file?

    -

    Forma breve quando basta l'esito, forma lunga quando conta il motivo:

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - Gli esiti sono accept, reject, sanitize e - unspecified. I motivi sono un elenco chiuso così un report può raggrupparli: - content_malformed, count_limit, dimensions_limit, - duplicate, encoding_invalid, extension_rule, - filename_invalid, filename_too_long, filename_traversal, - malware_signature, mime_mismatch, nesting_depth, - none, size_limit e size_zero. -

    -

    - Un motivo nomina la regola in gioco, non il verdetto. Ecco perché lo stesso motivo - può stare sotto l'uno o l'altro esito - un file un byte sotto un limite è accept, e - la regola in questione resta size_limit. -

    -
    - -
    -

    Cosa c'è nel manifest?

    -

    - Viene scritto accanto ai file alla fine di ogni esecuzione, compresa un'esecuzione interrotta. Una - voce per file: -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "0.6.0-rc1" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - Un recipe_hash viene aggiunto quando l'esecuzione viene da una ricetta, e - preset con overrides quando viene da un preset, così un manifest si - può sempre ricondurre a ciò che lo ha prodotto. -

    -

    - Ogni voce porta anche target_id, l'id del target della ricetta che ha prodotto il file, - e summary.by_target conta i file a cui è arrivato ciascun target. Una ricetta con - più target si può quindi controllare target per target senza leggere i nomi dei file. -

    -
    - -
    -

    Cos'è un preset?

    -

    - Un set di file pronto che risponde a una domanda di test comune, così non devi progettare il set tu. - I preset sono ricette ordinarie sotto il cofano, e eject stampa la ricetta così - puoi modificarla da lì. Ogni preset ha una pagina tutta sua con cosa - trova di solito, cosa c'è nel set e ogni impostazione che accetta. -

    +
    +

    Pagine della documentazione

    • -

      Vuoto e minimo

      -

      Un file valido e piccolo quanto il formato consente passa?

      -

      empty-and-minimal

      +

      Installazione EN

      +

      Scaricare per Windows, macOS o Linux, verificare l'archivio o installare con Docker, npm, pip o Go.

    • -
    • -

      Gestione dei nomi di file

      -

      Il mio sistema salverà, mostrerà e restituirà un nome di file che non si aspettava?

      -

      filename-handling

      +
    • +

      Primi passi EN

      +

      Un primo file di dimensione esatta, poi diecimila, verificati, rimossi e scritti come ricetta.

    • -
    • -

      Dimensioni delle immagini

      -

      Il mio sistema accetta immagini nelle dimensioni usate da schermi e piattaforme?

      -

      picture-sizes

      +
    • +

      Comandi EN

      +

      Ogni comando e ogni opzione con il valore predefinito, e tutti i codici di uscita.

      +
    • +
    • +

      Scrivere ricette EN

      +

      Ogni chiave di una ricetta, dimensioni, nomi dei file, reazioni attese, danni, archivi e preset.

    • -

      Limiti di dimensione

      -

      Un limite di dimensione viene applicato esattamente dove è dichiarato?

      -

      size-boundaries

      +

      Raccolta di ricette EN

      +

      Ricette pronte da scaricare per upload, importazioni, archivi, email, contenuti multimediali, CI e file in massa.

      +
    • +
    • +

      Manifest EN

      +

      Ogni campo di manifest.json e come lo legge un test.

    • -

      Importazione di tabelle

      -

      La mia importazione di tabelle regge a ciò che esportano gli strumenti reali?

      -

      tabular-import

      +

      Impostazioni dei formati EN

      +

      Ogni impostazione di ogni formato, con i valori accettati e il valore predefinito.

    • -

      Codifica del testo

      -

      Il mio lettore sa in quale codifica è un file, o tira a indovinare?

      -

      text-encoding

      +

      Framework di test EN

      +

      I file dentro pytest, Playwright, Vitest e node:test.

      +
    • +
    • +

      Applicazione desktop EN

      +

      La finestra, schermata per schermata.

    • -

      Validazione dell'upload

      -

      Il mio modulo di upload accetta ciò che deve e respinge il resto?

      -

      upload-validation

      +

      Strumenti

      +

      Strumenti offline per i file che hai già: se un archivio si decomprime in sicurezza, zip slip e zip bomb compresi, e verificare o scrivere checksum SHA-256.

    -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show ti dice quanto costerebbe il set prima di costruirlo, e dice apertamente quando un - numero è un segnaposto nostro anziché un limite tuo. -

    -
    -

    Cosa significano i codici di uscita?

    -

    - Ogni conclusione ha il suo codice, l'output leggibile da macchina va sullo standard output, e - un'esecuzione fallita non vi stampa nulla. La tabella è un contratto congelato - cambiare il - significato di un codice richiede una versione maggiore. -

    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    CodiceSignificato
    0Tutto ha funzionato.
    1Un errore imprevisto dentro lo strumento.
    2Comando od opzione errati.
    3La ricetta non è valida.
    4Il formato non può fare ciò che è stato chiesto.
    5Una lettura o una scrittura è fallita.
    6Spazio su disco insufficiente.
    7verify ha trovato una discrepanza.
    8L'esecuzione è terminata ma non tutto è stato prodotto.
    130Interrotto con Ctrl+C.
    143Fermato da un segnale, che è l'aspetto di un timeout della CI.
    -
    -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - Un'esecuzione fermata con Ctrl+C lascia comunque un manifest e non lascia mai un file scritto a - metà, così un job annullato può ancora essere ripulito dal successivo. -

    -

    - Workflow pronti per GitHub Actions e GitLab CI: come generare file - di test in una pipeline CI. -

    +
    +

    Che cosa fa lo strumento, argomento per argomento

    +
      +
    • +

      Formati

      +

      Tutti i formati che il generatore produce, il file più piccolo possibile per ciascuno e le impostazioni che accetta. Tutti i 32 si aprono nel loro programma.

      +
    • +
    • +

      Preset

      +

      Set pronti di file di test, ognuno risponde a una domanda: limiti di upload, nomi dei file, codifiche, importazione di tabelle, file vuoti e validazione.

      +
    • +
    • +

      File corrotti

      +

      Un file rotto di proposito, della dimensione esatta, con un manifest che dice che il tuo sistema deve rifiutarlo. Per testare validazione degli upload e parser.

      +
    • +
    • +

      File di esempio

      +

      File di test e di esempio da scaricare: ogni formato da 1 MB, PDF, Word ed Excel corrotti, tabelle CSV e immagini segnaposto, ognuno con il suo SHA-256.

      +
    • +
    • +

      Casi di test upload

      +

      Casi di test per l'upload di file: limite di dimensione, file vuoti e corrotti, tipo sbagliato, nomi inattesi e archivi, ognuno con il file che lo verifica.

      +
    • +
    • +

      File di test in CI

      +

      Genera file di test nella pipeline invece di committare binari: workflow GitHub Actions, job GitLab, codici di uscita e la trappola di PowerShell.

      +
    • +
    • +

      Dimensione esatta

      +

      fsutil, dd, truncate e mkfile, ciascuno misurato sul proprio sistema, e perché un file fatto così non è un PDF né un PNG quando un test ne richiede uno.

      +
    • +
    -
    -

    Esiste una finestra desktop?

    -

    - Sì, lo stesso motore con una finestra sopra, per il test che non è automatizzato. Non è una versione - ridotta: un test confronta le due interfacce capacità per capacità, e tutto ciò che può fare - solo una delle due va dichiarato e giustificato invece di divergere in silenzio. -

    +
    +

    Ancora bloccato?

    - Le schermate sono un lotto, i preset, più lotti insieme e Informazioni. Mostra quanto costerebbe - un'esecuzione prima di scrivere qualsiasi cosa, riporta l'avanzamento mentre gira e si può - annullare a metà senza lasciare un file scritto a metà. Non apre ancora un file di ricetta - per - ora le ricette sono una faccenda da riga di comando, e la finestra costruisce i suoi lotti nel - modulo. + tfg <command> --help mostra nel terminale che cosa accetta un comando. Ogni rifiuto nomina l'impostazione a cui si riferisce, il motivo e un valore che funzionerebbe. Se qualcosa non si comporta come dice una pagina, segnalalo. È un errore della pagina o del programma.

    diff --git a/web/public/it/strumenti/index.html b/web/public/it/strumenti/index.html index 0b0eb20b..4cf23ac4 100644 --- a/web/public/it/strumenti/index.html +++ b/web/public/it/strumenti/index.html @@ -151,6 +151,21 @@
    +

    Documentazione

    Controllare un archivio prima di decomprimerlo, e verificare i checksum

    diff --git a/web/public/ja/docs/index.html b/web/public/ja/docs/index.html index 73acea51..530d8a47 100644 --- a/web/public/ja/docs/index.html +++ b/web/public/ja/docs/index.html @@ -147,342 +147,93 @@

    ドキュメント

    - ツールの機能を、実際に寄せられる質問の形で整理しています。リポジトリのREADMEが完全なリファレンスで、ダウンロードしたビルドと常に一致しています。 + tfg のインストール、最初のテストファイルの作成、そしてプログラムが受け取り書き出すすべて。すべてのコマンドとフラグ、レシピのすべてのキー、マニフェストのすべてのフィールド、すべての形式のすべての設定です。これらのページは英語です。サイトを作るたびにプログラム自身から生成されるので、ダウンロードするバージョンの動作と常に一致します。

    -
    -

    どんなコマンドがありますか。

    -

    それぞれが1つのことだけを行います。

    -
    tfg generate    レシピまたはフラグからファイルを生成する
    -tfg validate    レシピを検査し、何も書き込まない
    -tfg verify      ディレクトリをマニフェストと照合する
    -tfg cleanup     マニフェストに載っているファイルを削除する
    -tfg recipe fmt  レシピを整形して出力する
    -tfg preset      名前の付いたテストの疑問からファイルセットを作る
    -tfg formats     このビルドが対応する形式を一覧表示する
    -tfg damage      このビルドがファイルを意図的に壊す方法を一覧表示する
    -tfg tool        手元にあるファイル向けの小さなツール
    -tfg version     ツールのバージョンを表示する
    -tfg license     ライセンスと、生成ファイルにとっての意味を表示する
    -

    - tfg toolには、展開前のアーカイブの検査など、手元にあるファイル向けのツールがあります。それぞれの説明はツールにあります。 -

    -
    - -
    -

    正確なサイズのファイルを1つ生成するには。

    -

    - 形式、サイズ、出力先を指定します。サイズは1024単位で数えるため、2mbは2097152バイトです。バイト数をそのまま指定することもでき、--size - 10485761はちょうどその数のバイトを要求します。 -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    generateで便利なフラグ:

    -
    - - - - - - - - - - - - - - - - - -
    フラグ動作
    --format <id>ファイルの形式。例:txt
    --size <size>各ファイルの正確なサイズ。10mbのような指定、またはバイト数
    --size-range <a-b>範囲からファイルごとに決めるサイズ。例:1kb-8kb。抽選はシードから決まります
    --boundary <size>制限の前後の3ファイル。1バイト下、制限値ちょうど、1バイト上
    --count <n>作成するファイル数。既定は1
    --name <template>名前のテンプレート。例:invoice_{index:04}.txt
    --out <dir>書き込み先のディレクトリ
    --seed <n>実行のシード。同じシードなら同じバイトになります
    --set <k>=<v>形式の設定。繰り返し指定できます
    --damage <name>ファイルを意図的に壊します。繰り返し指定でき、順番に適用されます。一覧はtfg damageで確認できます
    --expected <outcome>accept、reject、sanitize、unspecified
    --dry-run数えて表示するだけで、何も書き込みません
    --jsonマニフェストを標準出力に書き出します
    -
    -
    - -
    -

    意図的に壊れたファイルを作るには。

    -

    - このツールが書き込むそれ以外のファイルは、構造上すべて正しく、アップロード検証が問う3つの疑問のうち2つに答えます。--damageは3つ目、つまりファイルがそもそも開けるかに答えます。ファイルは通常どおり生成されてから壊されるため、要求したサイズのままです。 -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - 設定はコロンの後ろに書きます。フラグは繰り返せて、書いた順に適用されます。tfg damageは、このビルドで何ができるか、それぞれが何を受け付けるかを一覧表示します。 -

    -

    レシピでは、キーは名前または設定のリストになります。

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - 壊されたファイルには、マニフェストでexpected: - rejectが付き、横に壊した内容が記録されます。次の2つは、何かを書き込む前に拒否されます。どちらもマニフェストの記述と食い違うファイルをディスクに残してしまうためです。 -

    -
      -
    • 破壊に必要なサイズより小さいファイル。変更されないまま出てきてしまうため
    • -
    • - 破壊と併記されたexpected: - accept。どのファイルもそれを満たせないためです。テスト対象のシステムがファイルを修復する想定ならsanitizeを、まさにそれが調べたい点ならunspecifiedを書いてください -
    • -
    -

    - 3つ目は事前には分かりません。破壊が実行されても1バイトも変わらなかった場合、そのファイルは書き込まれずに破棄されます。実行は続き、どのファイルだったかを伝え、一部のみ完了した終了コードで終わります。 -

    -

    - 手順を追って、マニフェストを読むテストつきで説明します。テスト用の破損ファイルを作る方法。 -

    -
    - -
    -

    レシピはどんな見た目ですか。

    -

    - レシピは、実行全体を記述するYAMLファイルです。テストの隣にコミットすれば、フィクスチャはリポジトリ内のバイナリではなくなります。数百文字のファイルから、誰でもバイト単位で再構築できます。 -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - 各ターゲットには、size、size-range、boundary、containsのうち、ちょうど1つが必要です。2つはエラーで、ゼロもエラーです。無効なレシピはファイルを1つも書き込まず、最初の問題だけでなくすべての問題をまとめて報告し、それぞれ該当する設定名を示します。 -

    -
    - -
    -

    システムがファイルをどう扱うべきかを宣言するには。

    -

    結果だけで足りるなら短い形式を、理由が重要なら長い形式を使います。

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - 結果はaccept、reject、sanitize、unspecifiedです。理由は閉じたリストで、レポートで理由ごとにグループ化できます。content_malformed、count_limit、dimensions_limit、duplicate、encoding_invalid、extension_rule、filename_invalid、filename_too_long、filename_traversal、malware_signature、mime_mismatch、nesting_depth、none、size_limit、size_zero。 -

    -

    - 理由が示すのは判定ではなく問題になっているルールです。そのため、同じ理由が両方の結果の下に現れることがあります。制限より1バイト小さいファイルはacceptですが、対象となるルールは依然としてsize_limitです。 -

    -
    - -
    -

    マニフェストには何が入っていますか。

    -

    - 中断された実行も含め、すべての実行の終了時にファイルの隣へ書き出されます。ファイルごとに1項目です。 -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "0.6.0-rc1" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - 実行がレシピから来た場合はrecipe_hashが、プリセットから来た場合はpresetとoverridesが追加されるため、マニフェストは常に生成元までたどれます。 -

    -

    - 各項目には、ファイルを生成したレシピ内のターゲットのIDであるtarget_idも入り、summary.by_targetが各ターゲットのファイル数を数えます。複数のターゲットを持つレシピも、ファイル名を読まずにターゲットごとに確認できます。 -

    -
    - -
    -

    プリセットとは何ですか。

    -

    - 一般的なテストの疑問に答える既製のファイルセットで、セットを自分で設計する必要がありません。プリセットの中身は普通のレシピで、ejectがそのレシピを出力するので、そこから編集できます。各プリセットには、普通は何を見つけるか、セットの内容、受け付ける設定をまとめた専用ページがあります。 -

    +
    +

    ドキュメントのページ

    • -

      空ファイルと最小ファイル

      -

      形式が許す最小サイズの有効なファイルは通るでしょうか。

      -

      empty-and-minimal

      +

      インストール EN

      +

      Windows、macOS、Linux 用をダウンロードしてアーカイブを確認するか、Docker、npm、pip、Go でインストールします。

    • -
    • -

      ファイル名の扱い

      -

      想定外のファイル名を、システムは保存し、表示し、返せるでしょうか。

      -

      filename-handling

      +
    • +

      はじめに EN

      +

      正確なサイズの最初のファイル、次に一万個のファイルを作り、確認し、削除し、レシピとして書き残します。

    • -
    • -

      画像サイズ

      -

      画面やプラットフォームが使うサイズの画像を、システムは受け付けるでしょうか。

      -

      picture-sizes

      +
    • +

      コマンド EN

      +

      すべてのコマンドとすべてのフラグ、その既定値、そしてすべての終了コード。

      +
    • +
    • +

      レシピの書き方 EN

      +

      レシピのすべてのキー、サイズ、ファイル名、期待される反応、破損、アーカイブ、プリセット。

    • -

      サイズの境界

      -

      サイズ制限は、宣言された位置ちょうどで適用されているでしょうか。

      -

      size-boundaries

      +

      レシピ集 EN

      +

      アップロード、インポート、アーカイブ、メール、メディア、CI、大量ファイル向けの、ダウンロードしてすぐ使えるレシピ。

      +
    • +
    • +

      マニフェスト EN

      +

      manifest.json のすべてのフィールドと、テストでの読み方。

    • -

      表の取り込み

      -

      実際のツールが出力する表を、取り込みは正しく処理できるでしょうか。

      -

      tabular-import

      +

      形式の設定 EN

      +

      すべての形式のすべての設定と、受け付ける値、既定値。

    • -

      文字コード

      -

      読み取り側はファイルの文字コードを知っているのでしょうか。それとも推測でしょうか。

      -

      text-encoding

      +

      テストフレームワーク EN

      +

      pytest、Playwright、Vitest、node:test の中でファイルを使う方法。

      +
    • +
    • +

      デスクトップアプリ EN

      +

      ウィンドウを画面ごとに説明します。

    • -

      アップロードの検証

      -

      アップロードフォームは、受け入れるべきものを受け入れ、それ以外を拒否できるでしょうか。

      -

      upload-validation

      +

      ツール

      +

      手元のファイル向けのオフラインツール。zip slipやzip爆弾を含め、アーカイブを安全に展開できるかを調べ、SHA-256チェックサムを確認、作成します。

    -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - showは、セットを作る前にかかるコストを伝え、数値があなたの制限ではなくこちらの仮の値である場合は、はっきりそう伝えます。 -

    -
    -

    終了コードは何を意味しますか。

    -

    - 終わり方ごとに専用のコードがあり、機械可読な出力は標準出力に出て、失敗した実行はそこに何も出力しません。この表は凍結された契約で、コードの意味を変えるにはメジャーバージョンを上げる必要があります。 -

    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    コード意味
    0すべて正常に動作しました。
    1ツール内部で予期しないエラーが発生しました。
    2コマンドまたはフラグが正しくありません。
    3レシピが正しくありません。
    4その形式では要求された処理ができません。
    5読み取りまたは書き込みに失敗しました。
    6ディスクの空き容量が足りません。
    7verifyが不一致を見つけました。
    8実行は終了しましたが、すべてが生成されたわけではありません。
    130Ctrl+Cで中断されました。
    143シグナルで停止されました。CIのタイムアウトはこう見えます。
    -
    -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - Ctrl+Cで止めた実行でも、マニフェストは残り、書きかけのファイルは決して残りません。そのため、キャンセルされたジョブも次のジョブが片付けられます。 -

    -

    - GitHub ActionsとGitLab CI向けのすぐ使えるワークフロー。CIパイプラインでテストファイルを生成する方法。 -

    +
    +

    このツールでできること、テーマ別

    +
      +
    • +

      形式

      +

      生成できる全ファイル形式、形式ごとの最小ファイル、受け付ける設定の一覧です。全32形式が対応するソフトウェアで開けます。

      +
    • +
    • +

      プリセット

      +

      既製のテストファイルセット。それぞれが1つの疑問に答えます。アップロード制限、ファイル名、文字コード、表の取り込み、空ファイル、アップロード検証。

      +
    • +
    • +

      破損ファイル

      +

      意図的に壊した、サイズが正確なファイル。システムが拒否すべきことを示すマニフェスト付き。アップロード検証やパーサーのテスト用。

      +
    • +
    • +

      サンプルファイル

      +

      テスト用のサンプルファイルをダウンロード。全形式を1MBずつ、破損したPDF、Word、Excel、CSVの表、プレースホルダー画像。どれもSHA-256付きです。

      +
    • +
    • +

      アップロードのテストケース

      +

      ファイルアップロードのテストケース一覧。サイズ制限、空のファイルと破損ファイル、誤った種類、想定外のファイル名、アーカイブ。各ケースに検証用のファイルがあります。

      +
    • +
    • +

      CIでのテストファイル

      +

      バイナリをコミットする代わりに、パイプラインでテストファイルを生成。GitHub Actionsのワークフロー、GitLabのジョブ、終了コード、PowerShellの落とし穴。

      +
    • +
    • +

      正確なサイズ

      +

      fsutil、dd、truncate、mkfileを各OSで実測しました。テストがPDFやPNGを必要とするとき、この方法で作ったファイルでは足りない理由も解説します。

      +
    • +
    -
    -

    デスクトップウィンドウはありますか。

    -

    - はい。同じエンジンにウィンドウを載せたもので、スクリプト化しないテスト向けです。機能削減版ではありません。テストが2つのインターフェースを機能ごとに比較しており、片方にしかできないことは、静かに食い違うのではなく、宣言して理由を示す必要があります。 -

    +
    +

    まだ解決しませんか?

    - 画面は、単一バッチ、プリセット、複数バッチ同時、バージョン情報です。書き込む前に実行のコストを表示し、実行中は進捗を報告し、途中でキャンセルしても書きかけのファイルは残りません。レシピファイルはまだ開けません。レシピは今のところコマンドラインのもので、ウィンドウはフォームでバッチを組み立てます。 + tfg <command> --help を使うと、コマンドが受け取るものがターミナルに表示されます。拒否されたときは、どの設定についてか、その理由、そして使える値が必ず示されます。ページの説明どおりに動かない場合は 報告してください。それはページかプログラムの不具合です。

    diff --git a/web/public/ja/tools/index.html b/web/public/ja/tools/index.html index b89f4493..d75f1008 100644 --- a/web/public/ja/tools/index.html +++ b/web/public/ja/tools/index.html @@ -151,6 +151,21 @@
    +

    ドキュメント

    展開する前にアーカイブを検査し、チェックサムを確認する

    diff --git a/web/public/ko/docs/index.html b/web/public/ko/docs/index.html index 26cbc6df..9c238fb9 100644 --- a/web/public/ko/docs/index.html +++ b/web/public/ko/docs/index.html @@ -147,363 +147,93 @@

    문서

    - 도구가 하는 모든 일을 사람들이 실제로 가져오는 질문 형태로 정리했습니다. 저장소의 README가 전체 레퍼런스이며, - 내려받은 빌드와 항상 일치합니다. + tfg 설치 방법, 첫 테스트 파일 만들기, 그리고 프로그램이 받고 쓰는 모든 것. 모든 명령과 플래그, 레시피의 모든 키, 매니페스트의 모든 필드, 모든 형식의 모든 설정을 다룹니다. 이 페이지들은 영어로 되어 있습니다. 사이트를 만들 때마다 프로그램 자체에서 생성되므로 내려받는 버전이 하는 일과 항상 일치합니다.

    -
    -

    어떤 명령이 있나요?

    -

    각 명령은 한 가지 일만 합니다.

    -
    tfg generate    레시피나 플래그로 파일을 만든다
    -tfg validate    레시피를 검사하고 아무것도 쓰지 않는다
    -tfg verify      디렉터리를 매니페스트와 대조해 검사한다
    -tfg cleanup     매니페스트에 나열된 파일을 삭제한다
    -tfg recipe fmt  레시피를 정돈된 형태로 출력한다
    -tfg preset      이름 붙은 테스트 질문으로 파일 세트를 만든다
    -tfg formats     이 빌드가 지원하는 형식을 나열한다
    -tfg damage      이 빌드가 파일을 일부러 망가뜨릴 수 있는 방법을 나열한다
    -tfg tool        이미 가진 파일을 위한 작은 도구
    -tfg version     도구 버전을 출력한다
    -tfg license     라이선스와 생성된 파일에 대한 의미를 출력한다
    -

    - tfg tool에는 압축을 풀기 전에 아카이브를 검사하는 것처럼 이미 가진 파일을 위한 도구가 들어 있습니다. 각 도구는 도구에서 설명합니다. -

    -
    - -
    -

    정확한 크기의 파일 하나는 어떻게 만드나요?

    -

    - 형식, 크기, 저장 위치를 지정합니다. 크기는 1024 단위로 세므로 2mb는 2097152바이트입니다. 바이트 수를 그대로 써도 되므로 - --size 10485761은 정확히 그만큼을 요청합니다. -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    generate에서 유용한 플래그:

    -
    - - - - - - - - - - - - - - - - - -
    플래그동작
    --format <id>파일의 형식. 예: txt
    --size <size>각 파일의 정확한 크기. 10mb와 같은 값 또는 바이트 수
    --size-range <a-b>범위에서 파일마다 뽑는 크기. 예: 1kb-8kb. 추첨은 시드에서 나옵니다
    --boundary <size>한도 주변의 파일 세 개: 1바이트 아래, 한도 값, 1바이트 위
    --count <n>만들 파일 수. 기본값은 1
    --name <template>이름 템플릿. 예: invoice_{index:04}.txt
    --out <dir>쓸 디렉터리
    --seed <n>실행의 시드. 같은 시드는 같은 바이트를 만듭니다
    --set <k>=<v>형식 설정, 여러 번 지정할 수 있음
    --damage <name>파일을 일부러 망가뜨립니다. 여러 번 지정할 수 있으며 순서대로 적용됩니다. 목록은 tfg damage로 봅니다
    --expected <outcome>accept, reject, sanitize, unspecified
    --dry-run세어서 보여 주기만 하고 아무것도 쓰지 않음
    --json매니페스트를 표준 출력에 씀
    -
    -
    - -
    -

    일부러 망가진 파일은 어떻게 만드나요?

    -

    - 이 도구가 쓰는 다른 모든 파일은 구조상 올바르며, 이는 업로드 검증기가 던지는 세 가지 질문 중 두 가지에 답합니다. --damage는 세 번째, 곧 - 파일이 아예 열리는지에 답합니다. 파일은 정상적으로 만들어진 뒤 망가지므로 요청한 크기는 그대로입니다. -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - 설정은 콜론 뒤에 씁니다. 플래그는 반복할 수 있으며, 쓴 순서가 적용 순서입니다. tfg damage는 이 빌드가 할 수 있는 것과 각각이 받는 값을 - 나열합니다. -

    -

    레시피에서는 키가 이름 또는 설정의 목록입니다.

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - 손상된 파일은 매니페스트에서 expected: reject를 받고, 옆에 손상 내용이 기록됩니다. 두 가지는 아무것도 쓰기 전에 거부됩니다. 각각 - 매니페스트가 잘못 설명하는 파일을 디스크에 남기게 되기 때문입니다. -

    -
      -
    • 손상에 필요한 크기보다 작은 파일. 바뀌지 않은 채 나오기 때문입니다
    • -
    • - 손상과 함께 쓴 expected: accept. 어떤 파일도 이를 충족할 수 없기 때문입니다. 테스트 대상 시스템이 파일을 복구해야 한다면 - sanitize를, 바로 그것이 묻고 싶은 질문이라면 unspecified를 쓰세요 -
    • -
    -

    - 세 번째는 미리 알 수 없습니다. 손상이 실행되었는데 한 바이트도 바뀌지 않았다면 그 파일은 쓰이지 않고 버려집니다. 실행은 계속되고, 어떤 파일이었는지 알려 주며, 일부만 완료된 - 종료 코드로 끝납니다. -

    -

    - 단계별로, 매니페스트를 읽는 테스트와 함께 설명합니다. 테스트용 손상 파일을 만드는 방법. -

    -
    - -
    -

    레시피는 어떻게 생겼나요?

    -

    - 레시피는 실행 전체를 기술하는 YAML 파일입니다. 테스트 옆에 커밋하면 픽스처는 더 이상 저장소의 바이너리가 아닙니다. 몇백 자짜리 파일만 있으면 누구나 바이트 단위로 똑같이 - 다시 만들 수 있습니다. -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - 각 타깃에는 size, size-range, boundary, contains 중 - 정확히 하나가 필요합니다. 둘은 오류이고 하나도 없는 것도 오류입니다. 올바르지 않은 레시피는 파일을 하나도 쓰지 않으며, 첫 번째 문제만이 - 아니라 모든 문제를 한꺼번에 보고하고 각각 해당 설정의 이름을 알려 줍니다. -

    -
    - -
    -

    시스템이 파일을 어떻게 처리해야 하는지는 어떻게 선언하나요?

    -

    결과만 있으면 충분할 때는 짧은 형식을, 이유가 중요할 때는 긴 형식을 씁니다.

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - 결과는 accept, reject, sanitize, unspecified입니다. - 이유는 닫힌 목록이라 보고서가 이유별로 묶을 수 있습니다. content_malformed, count_limit, - dimensions_limit, duplicate, encoding_invalid, - extension_rule, filename_invalid, filename_too_long, - filename_traversal, malware_signature, mime_mismatch, - nesting_depth, none, size_limit, size_zero. -

    -

    - 이유가 가리키는 것은 판정이 아니라 문제가 되는 규칙입니다. 그래서 같은 이유가 어느 결과 아래에도 올 수 있습니다. 한도보다 1바이트 작은 파일은 - accept이지만, 관련된 규칙은 여전히 size_limit입니다. -

    -
    - -
    -

    매니페스트에는 무엇이 들어 있나요?

    -

    - 중단된 실행을 포함해 모든 실행이 끝날 때 파일 옆에 쓰입니다. 파일마다 항목이 하나씩 있습니다. -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "0.6.0-rc1" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - 실행이 레시피에서 왔다면 recipe_hash가, 프리셋에서 왔다면 preset과 overrides가 - 추가되므로, 매니페스트는 항상 그것을 만든 출처까지 추적할 수 있습니다. -

    -

    - 각 항목에는 파일을 만든 레시피 타깃의 id인 target_id도 들어 있고, summary.by_target은 각 타깃이 만든 파일 - 수를 셉니다. 따라서 타깃이 여러 개인 레시피도 파일 이름을 읽지 않고 타깃별로 확인할 수 있습니다. -

    -
    - -
    -

    프리셋이란 무엇인가요?

    -

    - 흔한 테스트 질문에 답하는 기성 파일 세트로, 세트를 직접 설계할 필요가 없습니다. 프리셋은 내부적으로 평범한 레시피이며, eject가 레시피를 출력하므로 - 거기서부터 편집할 수 있습니다. 각 프리셋에는 보통 무엇을 찾아내는지, 세트에 무엇이 들어 있는지, 어떤 설정을 받는지 설명하는 - 전용 페이지가 있습니다. -

    +
    +

    문서 페이지

    • -

      빈 파일과 최소 파일

      -

      형식이 허용하는 가장 작은 크기의 유효한 파일이 통과할까요?

      -

      empty-and-minimal

      +

      설치 EN

      +

      Windows, macOS, Linux용으로 내려받고 압축 파일을 확인하거나 Docker, npm, pip, Go로 설치합니다.

    • -
    • -

      파일 이름 처리

      -

      예상하지 못한 파일 이름을 시스템이 저장하고, 보여 주고, 돌려줄 수 있을까요?

      -

      filename-handling

      +
    • +

      시작하기 EN

      +

      정확한 크기의 첫 파일, 이어서 만 개의 파일을 만들고 확인하고 지운 뒤 레시피로 남깁니다.

    • -
    • -

      이미지 크기

      -

      화면과 플랫폼이 쓰는 크기의 이미지를 내 시스템이 받을까요?

      -

      picture-sizes

      +
    • +

      명령 EN

      +

      모든 명령과 모든 플래그, 그 기본값, 그리고 모든 종료 코드.

      +
    • +
    • +

      레시피 작성 EN

      +

      레시피의 모든 키, 크기, 파일 이름, 기대 반응, 손상, 압축 파일, 프리셋.

    • -

      크기 경계

      -

      크기 한도가 선언한 바로 그 지점에서 적용되고 있을까요?

      -

      size-boundaries

      +

      레시피 모음 EN

      +

      업로드, 가져오기, 압축 파일, 이메일, 미디어, CI, 대량 파일을 위해 바로 내려받을 수 있는 레시피.

      +
    • +
    • +

      매니페스트 EN

      +

      manifest.json의 모든 필드와 테스트에서 읽는 방법.

    • -

      표 가져오기

      -

      실제 도구가 내보내는 표를 제 가져오기 기능이 제대로 처리할까요?

      -

      tabular-import

      +

      형식 설정 EN

      +

      모든 형식의 모든 설정과 허용되는 값, 기본값.

    • -

      텍스트 인코딩

      -

      제 리더는 파일의 인코딩을 알고 있을까요, 아니면 추측하고 있을까요?

      -

      text-encoding

      +

      테스트 프레임워크 EN

      +

      pytest, Playwright, Vitest, node:test 안에서 파일을 쓰는 방법.

      +
    • +
    • +

      데스크톱 앱 EN

      +

      프로그램 창을 화면별로 설명합니다.

    • -

      업로드 검증

      -

      제 업로드 양식은 받아야 할 것을 받고 나머지는 거부할까요?

      -

      upload-validation

      +

      도구

      +

      이미 가진 파일을 위한 오프라인 도구. zip slip과 zip 폭탄을 포함해 아카이브를 안전하게 풀 수 있는지 보고, SHA-256 체크섬을 확인하거나 만듭니다.

    -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show는 세트를 만들기 전에 비용이 얼마나 드는지 알려 주고, 숫자가 여러분의 한도가 아니라 우리 쪽의 임시값일 때는 분명히 말해 줍니다. -

    -
    -

    종료 코드는 무엇을 뜻하나요?

    -

    - 끝나는 방식마다 고유한 코드가 있고, 기계가 읽을 수 있는 출력은 표준 출력으로 나가며, 실패한 실행은 거기에 아무것도 출력하지 않습니다. 이 표는 고정된 약속이며, 코드의 의미를 - 바꾸려면 메이저 버전을 올려야 합니다. -

    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    코드의미
    0모두 정상적으로 동작했습니다.
    1도구 내부에서 예기치 않은 오류가 발생했습니다.
    2명령 또는 플래그가 잘못되었습니다.
    3레시피가 올바르지 않습니다.
    4해당 형식으로는 요청한 작업을 할 수 없습니다.
    5읽기 또는 쓰기에 실패했습니다.
    6디스크 공간이 부족합니다.
    7verify가 불일치를 발견했습니다.
    8실행은 끝났지만 모든 것이 만들어지지는 않았습니다.
    130Ctrl+C로 중단되었습니다.
    143시그널로 중지되었습니다. CI 시간 초과가 이렇게 보입니다.
    -
    -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - Ctrl+C로 멈춘 실행도 매니페스트는 남기고, 쓰다 만 파일은 절대 남기지 않으므로, 취소된 작업을 다음 작업이 정리할 수 있습니다. -

    -

    - GitHub Actions와 GitLab CI용으로 바로 쓸 수 있는 워크플로. CI 파이프라인에서 테스트 파일을 생성하는 - 방법. -

    +
    +

    이 도구가 하는 일, 주제별

    +
      +
    • +

      형식

      +

      이 생성기가 만드는 모든 파일 형식, 형식별 가능한 가장 작은 파일, 각 형식이 받는 설정. 32종 모두 해당 소프트웨어에서 열립니다.

      +
    • +
    • +

      프리셋

      +

      기성 테스트 파일 세트로, 각 세트가 하나의 테스트 질문에 답합니다. 업로드 한도, 파일 이름, 인코딩, 표 가져오기, 빈 파일, 업로드 검증.

      +
    • +
    • +

      손상 파일

      +

      일부러 망가뜨린, 크기가 정확한 파일. 시스템이 거부해야 함을 알리는 매니페스트가 딸려 옵니다. 업로드 검증과 파서 테스트용.

      +
    • +
    • +

      샘플 파일

      +

      테스트용 샘플 파일 다운로드. 모든 형식의 1MB 파일, 손상된 PDF, Word, Excel 파일, CSV 표, 자리 표시자 이미지를 SHA-256과 함께 제공합니다.

      +
    • +
    • +

      업로드 테스트 케이스

      +

      파일 업로드 테스트 케이스. 크기 한도, 빈 파일과 손상된 파일, 잘못된 유형, 예상하지 못한 파일 이름, 아카이브까지 케이스마다 확인할 파일이 있습니다.

      +
    • +
    • +

      CI의 테스트 파일

      +

      바이너리를 커밋하는 대신 파이프라인에서 테스트 파일을 생성하세요. GitHub Actions 워크플로, GitLab 작업, 종료 코드, PowerShell의 함정.

      +
    • +
    • +

      정확한 크기

      +

      fsutil, dd, truncate, mkfile을 각 시스템에서 직접 측정했으며, 테스트에 PDF나 PNG가 필요할 때 이렇게 만든 파일로 부족한 이유도 설명합니다.

      +
    • +
    -
    -

    데스크톱 창이 있나요?

    -

    - 네. 같은 엔진 위에 창을 얹은 것으로, 스크립트로 하지 않는 테스트를 위한 것입니다. 축소판이 아닙니다. 테스트가 두 인터페이스를 기능별로 비교하며, 한쪽만 할 수 있는 것은 - 조용히 벌어지는 대신 선언하고 이유를 밝혀야 합니다. -

    +
    +

    아직 막히셨나요?

    - 화면은 단일 배치, 프리셋, 여러 배치 동시 실행, 정보입니다. 무엇이든 쓰기 전에 실행 비용을 보여 주고, 실행 중에는 진행 상황을 알려 주며, 쓰다 만 파일을 남기지 않고 - 도중에 취소할 수 있습니다. 아직 레시피 파일은 열지 못합니다. 지금은 레시피가 명령줄의 몫이고, 창은 양식에서 배치를 구성합니다. + tfg <command> --help 명령은 터미널에서 해당 명령이 받는 값을 보여 줍니다. 거부될 때는 항상 어떤 설정 때문인지, 이유, 그리고 사용할 수 있는 값을 알려 줍니다. 페이지 설명과 다르게 동작하면 알려 주세요. 그것은 페이지나 프로그램의 버그입니다.

    diff --git a/web/public/ko/tools/index.html b/web/public/ko/tools/index.html index b3d3aacf..9dd9f546 100644 --- a/web/public/ko/tools/index.html +++ b/web/public/ko/tools/index.html @@ -151,6 +151,21 @@
    +

    문서

    압축을 풀기 전에 아카이브를 검사하고 체크섬 확인하기

    diff --git a/web/public/nl/documentatie/index.html b/web/public/nl/documentatie/index.html index d816ab3b..9c5b3b61 100644 --- a/web/public/nl/documentatie/index.html +++ b/web/public/nl/documentatie/index.html @@ -147,392 +147,93 @@

    Documentatie

    - Alles wat de tool doet, geordend als de vragen waarmee mensen echt komen. De - README in de repository is de volledige referentie en komt altijd - overeen met de build die je hebt gedownload. + Hoe u tfg installeert, uw eerste testbestanden maakt, en alles wat het programma aanneemt en schrijft: elke opdracht en elke optie, elke sleutel van een recept, elk veld van het manifest en elke instelling van elk formaat. Deze pagina's zijn in het Engels, omdat ze bij elke bouw van de site uit het programma zelf ontstaan en dus altijd zeggen wat de versie doet die u downloadt.

    -
    -

    Welke opdrachten zijn er?

    -

    Elke doet precies één ding:

    -
    tfg generate    bestanden maken, uit een recept of met opties
    -tfg validate    een recept controleren en niets schrijven
    -tfg verify      een map controleren tegen een manifest
    -tfg cleanup     de bestanden verwijderen die een manifest opsomt
    -tfg recipe fmt  een recept in zijn vaste vorm afdrukken
    -tfg preset      een set bestanden bouwen uit een benoemde testvraag
    -tfg formats     de formaten opsommen die deze build ondersteunt
    -tfg damage      de manieren opsommen waarop deze build een bestand met opzet kan beschadigen
    -tfg tool        kleine hulpmiddelen voor bestanden die je al hebt
    -tfg version     de versie van de tool tonen
    -tfg license     de licentie tonen en wat die betekent voor gegenereerde bestanden
    -

    - tfg tool bevat de hulpmiddelen voor bestanden die je al hebt, zoals een archief - controleren voordat je het uitpakt. Hulpmiddelen beschrijft elk ervan. -

    -
    - -
    -

    Hoe genereer ik één bestand van een exacte grootte?

    -

    - Noem het formaat, de grootte en waar het naartoe moet. Groottes tellen in 1024-tallen, dus - 2mb is 2097152 bytes. Een gewoon aantal bytes werkt ook, dus --size - 10485761 vraagt precies zoveel. -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    De nuttige opties van generate:

    -
    - - - - - - - - - - - - - - - - - -
    OptieWat het doet
    --format <id>formaat van de bestanden, bijvoorbeeld txt
    --size <size>exacte grootte van elk bestand, zoals 10mb of een gewoon aantal bytes
    --size-range <a-b>een grootte die per bestand uit een bereik wordt getrokken, zoals 1kb-8kb. De trekking komt uit de seed
    --boundary <size>drie bestanden rond een limiet: één byte eronder, de limiet, één byte erboven
    --count <n>hoeveel bestanden te maken. Standaard 1
    --name <template>naamsjabloon, bijvoorbeeld invoice_{index:04}.txt
    --out <dir>map om naartoe te schrijven
    --seed <n>seed van de run. Dezelfde seed geeft dezelfde bytes
    --set <k>=<v>een formaatinstelling, herhaalbaar
    --damage <name>de bestanden met opzet beschadigen, herhaalbaar en in volgorde toegepast. Draai tfg damage voor de lijst
    --expected <outcome>accept, reject, sanitize of unspecified
    --dry-runtellen en tonen, helemaal niets schrijven
    --jsonhet manifest naar de standaarduitvoer schrijven
    -
    -
    - -
    -

    Hoe maak ik een bestand dat met opzet kapot is?

    -

    - Elk ander bestand dat deze tool schrijft is correct per constructie, wat twee van de drie vragen - beantwoordt die een uploadvalidator stelt. --damage beantwoordt de derde - gaat het - bestand überhaupt open. Het bestand wordt normaal gemaakt en daarna beschadigd, dus het heeft - nog steeds de grootte die je vroeg. -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - Instellingen komen na een dubbele punt. De optie herhaalt zich, en de volgorde waarin je ze schrijft - is de volgorde waarin ze worden toegepast. tfg damage toont wat deze build kan en - wat elke variant accepteert. -

    -

    In een recept is de sleutel een lijst, van namen of van instellingen:

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - Een beschadigd bestand krijgt expected: reject in het manifest, met de beschadiging - ernaast vastgelegd. Twee dingen worden geweigerd voordat er iets wordt geschreven, omdat elk - anders een bestand op schijf zou zetten dat het manifest verkeerd beschrijft: -

    -
      -
    • een bestand dat kleiner is dan de beschadiging nodig heeft, omdat het ongewijzigd zou uitkomen
    • -
    • - expected: accept naast een beschadiging, omdat niets daaraan kan voldoen. Schrijf - sanitize als het geteste systeem het bestand moet repareren, of - unspecified als dat de vraag is die je stelt -
    • -
    -

    - Een derde is vooraf niet te weten. Als een beschadiging draait en geen enkele byte verschuift, wordt - dat bestand weggegooid in plaats van geschreven - de run gaat door, zegt om welk bestand het - ging en eindigt met de gedeeltelijke afsluitcode. -

    -

    - Stap voor stap, met een test die het manifest leest: hoe - maak je een beschadigd bestand om mee te testen. -

    -
    - -
    -

    Hoe ziet een recept eruit?

    -

    - Een recept is een YAML-bestand dat een hele run beschrijft. Commit het naast je tests en de fixtures - zijn geen binaries meer in je repository - iedereen kan ze byte voor byte opnieuw opbouwen uit - een bestand van een paar honderd tekens. -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - Elk target heeft precies één van deze sleutels nodig: size, size-range, - boundary of contains. Twee is een fout en geen ook. Een ongeldig - recept schrijft helemaal geen bestanden en meldt alle problemen tegelijk in - plaats van alleen het eerste, elk met de instelling waar het over gaat. -

    -
    - -
    -

    Hoe leg ik vast wat mijn systeem met een bestand moet doen?

    -

    Korte vorm als de uitkomst genoeg is, lange vorm als de reden ertoe doet:

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - De uitkomsten zijn accept, reject, sanitize en - unspecified. De redenen zijn een gesloten lijst zodat een rapport erop kan - groeperen: content_malformed, count_limit, - dimensions_limit, duplicate, encoding_invalid, - extension_rule, filename_invalid, filename_too_long, - filename_traversal, malware_signature, mime_mismatch, - nesting_depth, none, size_limit en - size_zero. -

    -

    - Een reden noemt de regel die in het spel is, niet het oordeel. Daarom kan dezelfde - reden onder beide uitkomsten staan - een bestand één byte onder een limiet is - accept, en de regel waar het om gaat is nog steeds size_limit. -

    -
    - -
    -

    Wat staat er in het manifest?

    -

    - Het wordt aan het einde van elke run naast de bestanden geschreven, ook bij een onderbroken run. Eén - item per bestand: -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "0.6.0-rc1" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - Er komt een recipe_hash bij als de run uit een recept kwam, en preset met - overrides als hij uit een preset kwam, zodat een manifest altijd te herleiden is - tot wat het maakte. -

    -

    - Elk item draagt ook target_id, de id van het target in het recept dat het bestand - maakte, en summary.by_target telt de bestanden waar elk target op uitkwam. Een - recept met meerdere targets kan zo target voor target worden gecontroleerd zonder bestandsnamen - te lezen. -

    -
    - -
    -

    Wat is een preset?

    -

    - Een kant-en-klare set bestanden die een veelvoorkomende testvraag beantwoordt, zodat je de set niet - zelf hoeft te ontwerpen. Presets zijn gewone recepten onder de motorkap, en eject - drukt het recept af zodat je het vanaf daar kunt bewerken. Elke preset heeft - een eigen pagina met wat hij meestal vindt, wat er in de set zit en - welke instellingen hij kent. -

    +
    +

    Pagina's van de documentatie

    • -

      Leeg en minimaal

      -

      Komt een geldig bestand dat zo klein is als het formaat toestaat door de controle?

      -

      empty-and-minimal

      +

      Installeren EN

      +

      Downloaden voor Windows, macOS of Linux, het archief controleren, of installeren met Docker, npm, pip of Go.

    • -
    • -

      Omgaan met bestandsnamen

      -

      Slaat mijn systeem een bestandsnaam op, toont en geeft het die terug, ook als het die niet verwachtte?

      -

      filename-handling

      +
    • +

      Aan de slag EN

      +

      Een eerste bestand van een exacte grootte, daarna tienduizend, gecontroleerd, verwijderd en vastgelegd als recept.

    • -
    • -

      Afbeeldingsformaten

      -

      Neemt mijn systeem afbeeldingen aan in de formaten die schermen en platforms gebruiken?

      -

      picture-sizes

      +
    • +

      Opdrachten EN

      +

      Elke opdracht en elke optie met de standaardwaarde, en alle afsluitcodes.

      +
    • +
    • +

      Recepten schrijven EN

      +

      Elke sleutel van een recept, groottes, bestandsnamen, verwachte reacties, beschadigingen, archieven en presets.

    • -

      Groottegrenzen

      -

      Wordt een groottelimiet precies afgedwongen waar hij is opgegeven?

      -

      size-boundaries

      +

      Receptengalerij EN

      +

      Kant-en-klare recepten om te downloaden voor uploads, imports, archieven, e-mail, media, CI en bulkbestanden.

      +
    • +
    • +

      Manifest EN

      +

      Elk veld van manifest.json en hoe een test het leest.

    • -

      Tabelimport

      -

      Overleeft mijn tabelimport wat echte tools exporteren?

      -

      tabular-import

      +

      Formaatinstellingen EN

      +

      Elke instelling van elk formaat, met de toegestane waarden en de standaardwaarde.

    • -

      Tekencodering

      -

      Weet mijn lezer in welke codering een bestand staat, of gokt hij?

      -

      text-encoding

      +

      Testframeworks EN

      +

      De bestanden in pytest, Playwright, Vitest en node:test.

      +
    • +
    • +

      Desktopapp EN

      +

      Het venster, scherm voor scherm.

    • -

      Uploadvalidatie

      -

      Neemt mijn uploadformulier aan wat het moet en weigert het de rest?

      -

      upload-validation

      +

      Hulpmiddelen

      +

      Offline hulpmiddelen voor je eigen bestanden: een archief voor het uitpakken nakijken op zip slip en zip-bommen, en SHA-256-checksums controleren of schrijven.

    -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show zegt je wat de set zou kosten voordat je hem bouwt, en zegt zonder omwegen wanneer - een getal een tijdelijke waarde van ons is in plaats van een limiet van jou. -

    -
    -

    Wat betekenen de afsluitcodes?

    -

    - Elk einde heeft zijn eigen code, machineleesbare uitvoer gaat naar de standaarduitvoer, en een - mislukte run drukt daar niets af. De tabel is een bevroren contract - de betekenis van een code - wijzigen vereist een major-versie. -

    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    CodeBetekenis
    0Alles werkte.
    1Een onverwachte fout in de tool.
    2Verkeerde opdracht of optie.
    3Het recept is niet geldig.
    4Het formaat kan niet wat er gevraagd werd.
    5Een lees- of schrijfactie is mislukt.
    6Niet genoeg schijfruimte.
    7verify vond een afwijking.
    8De run is klaar, maar niet alles is gemaakt.
    130Onderbroken met Ctrl+C.
    143Gestopt door een signaal, zo ziet een CI-timeout eruit.
    -
    -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - Een run die met Ctrl+C is gestopt laat nog steeds een manifest achter en nooit een half geschreven - bestand, zodat een afgebroken taak door de volgende nog kan worden opgeruimd. -

    -

    - Kant-en-klare workflows voor GitHub Actions en GitLab CI: hoe - genereer je testbestanden in een CI-pipeline. -

    +
    +

    Wat het hulpmiddel doet, per onderwerp

    +
      +
    • +

      Formaten

      +

      Alle bestandsformaten die deze generator maakt, het kleinst mogelijke bestand per formaat en hun instellingen. Alle 32 openen in hun eigen programma.

      +
    • +
    • +

      Presets

      +

      Kant-en-klare sets testbestanden, elk beantwoordt een testvraag: uploadlimieten, bestandsnamen, tekencoderingen, tabelimport, lege bestanden en uploadvalidatie.

      +
    • +
    • +

      Beschadigde bestanden

      +

      Een bestand dat met opzet kapot is, op exacte grootte, met een manifest dat zegt dat je systeem het moet weigeren. Voor het testen van uploadvalidatie en parsers.

      +
    • +
    • +

      Voorbeeldbestanden

      +

      Testbestanden en voorbeeldbestanden downloaden: elk formaat in 1 MB, beschadigde PDF-, Word- en Excel-bestanden, CSV-tabellen en placeholders, elk met SHA-256.

      +
    • +
    • +

      Testgevallen upload

      +

      Testgevallen voor bestandsupload: groottelimiet, lege en beschadigde bestanden, verkeerd type, onverwachte namen en archieven, elk met het bestand dat het test.

      +
    • +
    • +

      Testbestanden in CI

      +

      Genereer testbestanden in de pipeline in plaats van binaire bestanden te committen: GitHub Actions-workflow, GitLab-job, afsluitcodes en de PowerShell-valkuil.

      +
    • +
    • +

      Exacte grootte

      +

      fsutil, dd, truncate en mkfile, elk gemeten op het systeem waarvoor het bedoeld is, en waarom zo'n bestand geen PDF of PNG is wanneer een test dat nodig heeft.

      +
    • +
    -
    -

    Is er een bureaubladvenster?

    -

    - Ja, dezelfde engine met een venster erop, voor het testen dat niet geautomatiseerd is. Het is geen - uitgeklede versie: een test vergelijkt de twee interfaces mogelijkheid voor mogelijkheid, en - alles wat maar één van beide kan moet worden verklaard en gerechtvaardigd in plaats van - ongemerkt uit elkaar te drijven. -

    +
    +

    Komt u er nog niet uit?

    - De schermen zijn één batch, presets, meerdere batches tegelijk en info. Het toont wat een run zou - kosten voordat er iets wordt geschreven, meldt de voortgang terwijl het draait en kan halverwege - worden afgebroken zonder een half geschreven bestand achter te laten. Het opent nog geen - receptbestand - recepten zijn voorlopig iets van de opdrachtregel, en het venster bouwt zijn - batches in het formulier. + tfg <command> --help toont in de terminal wat een opdracht aanneemt. Elke weigering noemt de instelling waar het om gaat, de reden en een waarde die wel werkt. Als iets anders werkt dan een pagina hier zegt, meld het. Dan zit de fout in de pagina of in het programma.

    diff --git a/web/public/nl/hulpmiddelen/index.html b/web/public/nl/hulpmiddelen/index.html index 5ca5ffd9..b0551161 100644 --- a/web/public/nl/hulpmiddelen/index.html +++ b/web/public/nl/hulpmiddelen/index.html @@ -151,6 +151,21 @@
    +

    Documentatie

    Een archief controleren voor het uitpakken, en checksums verifiëren

    diff --git a/web/public/pl/dokumentacja/index.html b/web/public/pl/dokumentacja/index.html index 21bb65d1..94cfb890 100644 --- a/web/public/pl/dokumentacja/index.html +++ b/web/public/pl/dokumentacja/index.html @@ -147,386 +147,93 @@

    Dokumentacja

    - Wszystko, co narzędzie robi, ułożone jako pytania, z którymi ludzie naprawdę przychodzą. - README w repozytorium jest pełną dokumentacją i zawsze odpowiada - wersji, którą pobrałeś. + Jak zainstalować tfg, zrobić pierwsze pliki testowe i wszystko, co program przyjmuje i zapisuje: każda komenda i flaga, każdy klucz przepisu, każde pole manifestu i każde ustawienie każdego formatu. Te strony są po angielsku, bo powstają z samego programu przy każdym budowaniu strony, więc zawsze mówią to, co robi wersja, którą pobierasz.

    -
    -

    Jakie są komendy?

    -

    Każda robi jedną rzecz:

    -
    tfg generate    tworzy pliki, z przepisu albo z flag
    -tfg validate    sprawdza przepis i nic nie zapisuje
    -tfg verify      sprawdza katalog względem manifestu
    -tfg cleanup     usuwa pliki wypisane w manifeście
    -tfg recipe fmt  wypisuje przepis w postaci uporządkowanej
    -tfg preset      buduje zestaw plików z nazwanego pytania testowego
    -tfg formats     wypisuje formaty, które ta wersja obsługuje
    -tfg damage      wypisuje sposoby, którymi ta wersja umie celowo zepsuć plik
    -tfg tool        drobne czynności na plikach, które już masz
    -tfg version     wypisuje wersję narzędzia
    -tfg license     wypisuje licencję i to, co znaczy dla wygenerowanych plików
    -

    - tfg tool zawiera narzędzia do plików, które już masz, na przykład sprawdzanie archiwum - przed rozpakowaniem. Narzędzia opisują każde z nich. -

    -
    - -
    -

    Jak wygenerować jeden plik o dokładnym rozmiarze?

    -

    - Podaj format, rozmiar i katalog. Rozmiary liczą się po 1024, więc 2mb to 2097152 - bajty. Zwykła liczba bajtów też zadziała, więc --size 10485761 prosi dokładnie - o tyle. -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    Przydatne flagi komendy generate:

    -
    - - - - - - - - - - - - - - - - - -
    FlagaCo robi
    --format <id>format plików, na przykład txt
    --size <rozmiar>dokładny rozmiar każdego pliku, na przykład 10mb albo liczba bajtów
    --size-range <a-b>rozmiar losowany dla każdego pliku z zakresu, na przykład 1kb-8kb. Losowanie idzie z ziarna
    --boundary <rozmiar>trzy pliki wokół limitu: bajt pod, dokładnie limit, bajt nad
    --count <n>ile plików zapisać. Domyślnie 1
    --name <szablon>szablon nazwy, na przykład invoice_{index:04}.txt
    --out <katalog>katalog, do którego trafiają pliki
    --seed <n>ziarno przebiegu. To samo ziarno daje te same bajty
    --set <k>=<v>ustawienie formatu, można powtarzać
    --damage <nazwa>celowo psuje pliki, można powtarzać, stosowane po kolei. Listę wypisuje tfg damage
    --expected <wynik>accept, reject, sanitize albo unspecified
    --dry-runpolicz i pokaż, nie zapisuj niczego
    --jsonwypisz manifest na standardowe wyjście
    -
    -
    - -
    -

    Jak zrobić plik celowo zepsuty?

    -

    - Każdy inny plik, który to narzędzie zapisuje, jest poprawny z definicji, co odpowiada na dwa - z trzech pytań walidatora uploadu. --damage odpowiada na trzecie - czy plik w ogóle - się otwiera. Plik powstaje normalnie i dopiero potem zostaje zepsuty, więc dalej ma zamówiony - rozmiar. -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - Ustawienia idą po dwukropku. Flagę można powtarzać, a kolejność zapisu jest kolejnością - stosowania. tfg damage wypisuje, co ta wersja umie i co każde uszkodzenie - przyjmuje. -

    -

    W przepisie klucz jest listą, nazw albo ustawień:

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - Uszkodzony plik dostaje w manifeście expected: reject, a obok niego zapisane - uszkodzenie. Dwie rzeczy są odmawiane, zanim cokolwiek powstanie, bo każda zostawiłaby na - dysku plik, który manifest opisuje nieprawdziwie: -

    -
      -
    • plik mniejszy niż potrzebuje uszkodzenie, bo wyszedłby nietknięty
    • -
    • - expected: accept obok uszkodzenia, bo nic nie mogłoby tego spełnić. Napisz - sanitize, jeśli system pod testem ma plik naprawić, albo - unspecified, jeśli właśnie o to pytasz -
    • -
    -

    - Trzeciej rzeczy nie da się wiedzieć z góry. Jeśli uszkodzenie przebiegnie i nie ruszy ani - jednego bajtu, taki plik zostaje odrzucony zamiast zapisany - przebieg idzie dalej, mówi, - którego pliku to dotyczyło, i kończy się kodem częściowego wyniku. -

    -

    - Krok po kroku, z testem czytającym manifest: jak zrobić uszkodzony plik do testów. -

    -
    - -
    -

    Jak wygląda przepis?

    -

    - Przepis to plik YAML opisujący cały przebieg. Commitujesz go obok testów i dane testowe przestają - być binariami w repozytorium - każdy może je odtworzyć, co do bajta, z pliku o długości kilkuset - znaków. -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - Każdy cel potrzebuje dokładnie jednego z: size, size-range, - boundary albo contains. Dwa naraz to błąd, brak też. Niepoprawny przepis - nie tworzy ani jednego pliku i zgłasza wszystkie problemy naraz, a nie pierwszy - z brzegu, przy czym każdy nazywa ustawienie, o które chodzi. -

    -
    - -
    -

    Jak zadeklarować, co system ma zrobić z plikiem?

    -

    Krótka forma, gdy wystarczy sam wynik, i długa, gdy liczy się powód:

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - Wyniki to accept, reject, sanitize i - unspecified. Powody są zamkniętą listą, żeby raport mógł po nich grupować: - content_malformed, count_limit, dimensions_limit, - duplicate, encoding_invalid, extension_rule, - filename_invalid, filename_too_long, filename_traversal, - malware_signature, mime_mismatch, nesting_depth, - none, size_limit i size_zero. -

    -

    - Powód nazywa regułę, o którą chodzi, a nie werdykt. Dlatego ten sam powód może - stać pod jednym i pod drugim wynikiem - plik bajt pod limitem jest accept, a reguła, - której dotyczy, to dalej size_limit. -

    -
    - -
    -

    Co zawiera manifest?

    -

    - Powstaje obok plików na koniec każdego przebiegu, także takiego, który został przerwany. Jedna - pozycja na plik: -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "0.6.0-rc1" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - Do tego dochodzi recipe_hash, gdy przebieg pochodził z przepisu, oraz - preset i overrides, gdy pochodził z presetu - żeby manifest zawsze dało - się prześledzić z powrotem do tego, co go wyprodukowało. -

    -

    - Każdy wpis niesie też target_id, czyli id celu z przepisu, który - wyprodukował ten plik, a summary.by_target liczy pliki, które dał każdy cel. Przepis - z kilkoma celami da się dzięki temu sprawdzać cel po celu, bez czytania nazw plików. -

    -
    - -
    -

    Czym jest preset?

    -

    - To gotowy zestaw plików odpowiadający na częste pytanie testowe, żebyś nie musiał projektować - zestawu samodzielnie. Presety są pod spodem zwykłymi przepisami, a eject wypisuje ten - przepis, więc możesz go od tego miejsca edytować. Każdy preset ma - własną stronę: co zwykle znajduje, co jest w zestawie i jakie ustawienia - przyjmuje. -

    +
    +

    Strony dokumentacji

    • -

      Pliki puste i minimalne

      -

      Czy plik poprawny i najmniejszy, na jaki format pozwala, przechodzi?

      -

      empty-and-minimal

      +

      Instalacja EN

      +

      Pobierz na Windows, macOS albo Linuksa, sprawdź archiwum albo zainstaluj przez Dockera, npm, pip lub Go.

    • -
    • -

      Obsługa nazw plików

      -

      Czy mój system zapisze, pokaże i odda nazwę pliku, której się nie spodziewał?

      -

      filename-handling

      +
    • +

      Pierwsze kroki EN

      +

      Pierwszy plik o dokładnym rozmiarze, potem dziesięć tysięcy, sprawdzone, usunięte i zapisane jako przepis.

    • -
    • -

      Rozmiary obrazków

      -

      Czy mój system przyjmuje obrazki w rozmiarach, jakich używają ekrany i platformy?

      -

      picture-sizes

      +
    • +

      Komendy EN

      +

      Każda komenda i każda flaga z wartością domyślną oraz wszystkie kody wyjścia.

      +
    • +
    • +

      Pisanie przepisów EN

      +

      Każdy klucz przepisu, rozmiary, nazwy plików, oczekiwane reakcje, uszkodzenia, archiwa i presety.

    • -

      Granice rozmiaru

      -

      Czy limit rozmiaru działa dokładnie tam, gdzie jest zadeklarowany?

      -

      size-boundaries

      +

      Galeria przepisów EN

      +

      Gotowe przepisy do pobrania: uploady, importy, archiwa, e-maile, multimedia, CI i masowe pliki.

      +
    • +
    • +

      Manifest EN

      +

      Każde pole manifest.json i to, jak test je czyta.

    • -

      Import tabel

      -

      Czy import tabeli poradzi sobie z tym, co eksportują prawdziwe narzędzia?

      -

      tabular-import

      +

      Ustawienia formatów EN

      +

      Każde ustawienie każdego formatu z dopuszczalnymi wartościami i wartością domyślną.

    • -

      Kodowanie tekstu

      -

      Czy mój czytnik wie, w jakim kodowaniu jest plik, czy zgaduje?

      -

      text-encoding

      +

      Frameworki testowe EN

      +

      Pliki w testach pytest, Playwright, Vitest i node:test.

      +
    • +
    • +

      Aplikacja okienkowa EN

      +

      Okno programu, ekran po ekranie.

    • -

      Walidacja uploadu

      -

      Czy mój formularz przesyłania plików przyjmuje to, co powinien, i odrzuca resztę?

      -

      upload-validation

      +

      Narzędzia

      +

      Narzędzia offline do plików, które już masz: czy archiwum można bezpiecznie rozpakować (zip slip, zip bomb) oraz sprawdzanie i zapis sum SHA-256.

    -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show mówi, ile zestaw będzie kosztował, zanim go zbudujesz, i wprost zaznacza, kiedy - liczba jest naszą wartością zastępczą, a nie Twoim limitem. -

    -
    -

    Co znaczą kody wyjścia?

    -

    - Każde zakończenie ma własny kod, wyjście czytelne dla maszyny idzie na standardowe wyjście, - a nieudany przebieg nie pisze tam nic. Tabela jest zamrożonym kontraktem - zmiana znaczenia kodu - wymaga podniesienia wersji głównej. -

    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    KodZnaczenie
    0Wszystko się udało.
    1Nieoczekiwany błąd wewnątrz narzędzia.
    2Zła komenda albo flaga.
    3Przepis jest niepoprawny.
    4Format nie potrafi tego, o co poproszono.
    5Odczyt albo zapis się nie powiódł.
    6Za mało miejsca na dysku.
    7verify znalazło niezgodność.
    8Przebieg się zakończył, ale nie wszystko powstało.
    130Przerwane przez Ctrl+C.
    143Zatrzymane sygnałem - tak wygląda przekroczony czas w CI.
    -
    -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - Przebieg zatrzymany przez Ctrl+C i tak zostawia manifest i nigdy nie zostawia pliku zapisanego - w połowie, więc anulowane zadanie da się posprzątać następnym. -

    -

    - Gotowe workflow dla GitHub Actions i GitLab CI: jak generować pliki testowe w potoku CI. -

    +
    +

    Co robi narzędzie, temat po temacie

    +
      +
    • +

      Formaty

      +

      Wszystkie formaty, jakie generuje to narzędzie, najmniejszy możliwy plik każdego z nich i ustawienia, które przyjmuje. Każdy otwiera się w swoim programie.

      +
    • +
    • +

      Presety

      +

      Gotowe zestawy plików testowych, każdy odpowiada na jedno pytanie: limity uploadu, nazwy plików, kodowanie, import tabel, pliki puste i walidacja uploadu.

      +
    • +
    • +

      Uszkodzone pliki

      +

      Zrób plik zepsuty celowo, o dokładnie takim rozmiarze, jaki podasz, z manifestem mówiącym, że system powinien go odrzucić. Do testów walidacji uploadu i parserów.

      +
    • +
    • +

      Przykładowe pliki

      +

      Pliki testowe do pobrania: każdy z 32 formatów po 1 MB, uszkodzone PDF, Word i Excel, tabele CSV i obrazki zastępcze, każdy z sumą SHA-256.

      +
    • +
    • +

      Przypadki testowe uploadu

      +

      Lista przypadków testowych uploadu plików: limit rozmiaru, pusty i uszkodzony plik, zły typ, nietypowe nazwy i archiwa, każdy z plikiem, który go sprawdza.

      +
    • +
    • +

      Pliki testowe w CI

      +

      Generuj pliki testowe w potoku zamiast commitować binaria: workflow GitHub Actions, zadanie GitLaba, kody wyjścia przerywające build i pułapka PowerShella.

      +
    • +
    • +

      Rozmiar pliku

      +

      fsutil, dd, truncate i mkfile - polecenia zmierzone na trzech systemach, i dlaczego tak zrobiony plik nie jest PDF-em ani PNG-iem, gdy test tego potrzebuje.

      +
    • +
    -
    -

    Czy jest okno?

    -

    - Tak, ten sam silnik z oknem, do testowania, które nie jest skryptowane. Nie jest okrojoną wersją: - test porównuje obie powierzchnie możliwość po możliwości, a wszystko, co potrafi tylko jedna z nich, - musi być zadeklarowane i uzasadnione, zamiast po cichu się rozjeżdżać. -

    +
    +

    Nadal coś nie działa?

    - Ekrany to pojedynczy wsad, presety, kilka wsadów naraz i informacje o programie. Okno pokazuje, - ile przebieg będzie kosztował, zanim cokolwiek zapisze, melduje postęp w trakcie i da się je - przerwać w połowie bez zostawiania pliku zapisanego do połowy. Nie wczytuje jeszcze przepisu - z pliku - przepisy są na razie sprawą wiersza poleceń, a okno buduje swoje wsady w formularzu. + tfg <command> --help mówi w terminalu, co przyjmuje komenda. Każda odmowa nazywa ustawienie, którego dotyczy, mówi dlaczego i podaje wartość, która zadziała. Jeśli coś działa inaczej, niż mówi strona, zgłoś to. To błąd strony albo programu.

    diff --git a/web/public/pl/narzedzia/index.html b/web/public/pl/narzedzia/index.html index 499bb10b..79c5e78b 100644 --- a/web/public/pl/narzedzia/index.html +++ b/web/public/pl/narzedzia/index.html @@ -151,6 +151,21 @@
    +

    Dokumentacja

    Sprawdź archiwum przed rozpakowaniem i sumy kontrolne

    diff --git a/web/public/pt-br/documentacao/index.html b/web/public/pt-br/documentacao/index.html index 0e26c56c..ccccf539 100644 --- a/web/public/pt-br/documentacao/index.html +++ b/web/public/pt-br/documentacao/index.html @@ -147,387 +147,93 @@

    Documentação

    - Tudo o que a ferramenta faz, organizado como as perguntas com que as pessoas realmente chegam. O - README do repositório é a referência completa e sempre corresponde - à versão que você baixou. + Como instalar o tfg, criar seus primeiros arquivos de teste e tudo o que o programa aceita e escreve: cada comando e cada opção, cada chave de uma receita, cada campo do manifesto e cada configuração de cada formato. Estas páginas estão em inglês, porque são geradas pelo próprio programa a cada construção do site e por isso sempre dizem o que faz a versão que você baixa.

    -
    -

    Quais comandos existem?

    -

    Cada um faz uma única coisa:

    -
    tfg generate    produzir arquivos, a partir de uma receita ou de opções
    -tfg validate    verificar uma receita sem escrever nada
    -tfg verify      verificar um diretório contra um manifesto
    -tfg cleanup     remover os arquivos que um manifesto lista
    -tfg recipe fmt  imprimir uma receita na sua forma normalizada
    -tfg preset      montar um conjunto de arquivos a partir de uma pergunta de teste nomeada
    -tfg formats     listar os formatos que esta versão suporta
    -tfg damage      listar as formas como esta versão pode quebrar um arquivo de propósito
    -tfg tool        pequenas utilidades para arquivos que você já tem
    -tfg version     imprimir a versão da ferramenta
    -tfg license     imprimir a licença e o que ela significa para os arquivos gerados
    -

    - tfg tool reúne as ferramentas para arquivos que você já tem, como checar um arquivo - compactado antes de descompactá-lo. Ferramentas descreve cada uma. -

    -
    - -
    -

    Como gero um único arquivo de tamanho exato?

    -

    - Informe o formato, o tamanho e o destino. Os tamanhos contam de 1024 em 1024, então 2mb - são 2097152 bytes. Uma contagem simples de bytes também funciona, então --size - 10485761 pede exatamente essa quantidade. -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    As opções úteis de generate:

    -
    - - - - - - - - - - - - - - - - - -
    OpçãoO que faz
    --format <id>formato dos arquivos, por exemplo txt
    --size <size>tamanho exato de cada arquivo, como 10mb ou uma contagem simples de bytes
    --size-range <a-b>um tamanho sorteado por arquivo dentro de um intervalo, como 1kb-8kb. O sorteio vem do seed
    --boundary <size>três arquivos ao redor de um limite: um byte abaixo, o limite, um byte acima
    --count <n>quantos arquivos produzir. Padrão 1
    --name <template>modelo de nome, por exemplo invoice_{index:04}.txt
    --out <dir>diretório onde escrever
    --seed <n>seed da execução. O mesmo seed dá os mesmos bytes
    --set <k>=<v>uma configuração de formato, repetível
    --damage <name>quebrar os arquivos de propósito, repetível e aplicado em ordem. Rode tfg damage para ver a lista
    --expected <outcome>accept, reject, sanitize ou unspecified
    --dry-runcontar e mostrar, sem escrever absolutamente nada
    --jsonescrever o manifesto na saída padrão
    -
    -
    - -
    -

    Como faço um arquivo quebrado de propósito?

    -

    - Todo outro arquivo que esta ferramenta escreve é correto por construção, o que responde a duas das - três perguntas que um validador de upload faz. --damage responde à terceira - se o - arquivo abre, afinal. O arquivo é produzido normalmente e depois quebrado, então continua com o - tamanho que você pediu. -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - As configurações vão depois de dois-pontos. A opção se repete, e a ordem em que você as escreve é a - ordem em que são aplicadas. tfg damage lista o que esta versão pode fazer e o que - cada uma aceita. -

    -

    Em uma receita a chave é uma lista, de nomes ou de configurações:

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - Um arquivo danificado recebe expected: reject no manifesto, com o dano registrado ao - lado. Duas coisas são recusadas antes de escrever qualquer coisa, porque cada uma deixaria no - disco um arquivo que o manifesto descreve errado: -

    -
      -
    • um arquivo menor do que o dano precisa, porque sairia sem alteração
    • -
    • - expected: accept ao lado de um dano, porque nada poderia cumpri-lo. Escreva - sanitize se o sistema sob teste deve reparar o arquivo, ou - unspecified se essa é a pergunta que você está fazendo -
    • -
    -

    - Uma terceira não pode ser conhecida de antemão. Se um dano roda e não move nenhum byte, esse arquivo - é descartado em vez de escrito - a execução continua, diz qual arquivo foi e termina com o - código de saída parcial. -

    -

    - Passo a passo, com um teste que lê o manifesto: como - criar um arquivo corrompido para testes. -

    -
    - -
    -

    Como é uma receita?

    -

    - Uma receita é um arquivo YAML que descreve uma execução inteira. Versione-a ao lado dos seus testes - e as fixtures deixam de ser binários no seu repositório - qualquer pessoa pode reconstruí-las, - byte a byte, a partir de um arquivo de algumas centenas de caracteres. -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - Cada target precisa de exatamente uma destas chaves: size, size-range, - boundary ou contains. Duas é um erro e nenhuma também. Uma receita - inválida escreve nenhum arquivo e relata todos os problemas de uma vez em vez - de só o primeiro, cada um nomeando a configuração a que se refere. -

    -
    - -
    -

    Como declaro o que meu sistema deve fazer com um arquivo?

    -

    Forma curta quando o resultado basta, forma longa quando o motivo importa:

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - Os resultados são accept, reject, sanitize e - unspecified. Os motivos são uma lista fechada para que um relatório possa agrupar - por eles: content_malformed, count_limit, - dimensions_limit, duplicate, encoding_invalid, - extension_rule, filename_invalid, filename_too_long, - filename_traversal, malware_signature, mime_mismatch, - nesting_depth, none, size_limit e size_zero. -

    -

    - Um motivo nomeia a regra em jogo, não o veredito. Por isso o mesmo motivo pode - ficar sob qualquer um dos resultados - um arquivo um byte abaixo de um limite é - accept, e a regra de que se trata continua sendo size_limit. -

    -
    - -
    -

    O que há no manifesto?

    -

    - Ele é escrito ao lado dos arquivos no fim de cada execução, inclusive de uma execução interrompida. - Uma entrada por arquivo: -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "0.6.0-rc1" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - Um recipe_hash é adicionado quando a execução veio de uma receita, e - preset com overrides quando veio de um preset, de modo que um - manifesto sempre pode ser rastreado até o que o produziu. -

    -

    - Cada entrada também traz target_id, o id do target da receita que produziu o arquivo, e - summary.by_target conta os arquivos a que cada target chegou. Uma receita com - vários targets pode assim ser verificada target por target sem ler nomes de arquivo. -

    -
    - -
    -

    O que é um preset?

    -

    - Um conjunto de arquivos pronto que responde a uma pergunta de teste comum, para que você não precise - desenhar o conjunto. Presets são receitas comuns por baixo, e eject imprime a - receita para você editá-la a partir dali. Cada preset tem uma página - própria com o que costuma encontrar, o que há no conjunto e cada configuração que aceita. -

    +
    +

    Páginas da documentação

    • -

      Vazio e mínimo

      -

      Um arquivo válido e tão pequeno quanto o formato permite passa?

      -

      empty-and-minimal

      +

      Instalação EN

      +

      Baixar para Windows, macOS ou Linux, verificar o arquivo ou instalar com Docker, npm, pip ou Go.

    • -
    • -

      Tratamento de nomes de arquivo

      -

      Meu sistema vai guardar, mostrar e devolver um nome de arquivo que ele não esperava?

      -

      filename-handling

      +
    • +

      Primeiros passos EN

      +

      Um primeiro arquivo de tamanho exato, depois dez mil, verificados, removidos e escritos como receita.

    • -
    • -

      Tamanhos de imagem

      -

      Meu sistema aceita imagens nos tamanhos que telas e plataformas usam?

      -

      picture-sizes

      +
    • +

      Comandos EN

      +

      Cada comando e cada opção com seu valor padrão, e todos os códigos de saída.

      +
    • +
    • +

      Escrever receitas EN

      +

      Cada chave de uma receita, tamanhos, nomes de arquivo, reações esperadas, danos, arquivos compactados e presets.

    • -

      Limites de tamanho

      -

      Um limite de tamanho é aplicado exatamente onde foi declarado?

      -

      size-boundaries

      +

      Galeria de receitas EN

      +

      Receitas prontas para baixar para uploads, importações, arquivos compactados, e-mail, mídia, CI e arquivos em massa.

      +
    • +
    • +

      Manifesto EN

      +

      Cada campo do manifest.json e como um teste o lê.

    • -

      Importação de tabelas

      -

      A minha importação de tabelas sobrevive ao que ferramentas reais exportam?

      -

      tabular-import

      +

      Configurações dos formatos EN

      +

      Cada configuração de cada formato, com os valores aceitos e o valor padrão.

    • -

      Codificação de texto

      -

      Meu leitor sabe em que codificação um arquivo está, ou está adivinhando?

      -

      text-encoding

      +

      Frameworks de teste EN

      +

      Os arquivos dentro do pytest, Playwright, Vitest e node:test.

      +
    • +
    • +

      Aplicativo de desktop EN

      +

      A janela, tela por tela.

    • -

      Validação de upload

      -

      Meu formulário de upload aceita o que deve e recusa o resto?

      -

      upload-validation

      +

      Ferramentas

      +

      Ferramentas offline para os seus arquivos: veja se um arquivo compactado é seguro para descompactar (zip slip, zip bomb) e confira ou grave somas SHA-256.

    -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show diz quanto o conjunto custaria antes de você montá-lo, e diz abertamente quando um - número é um valor provisório nosso, e não um limite seu. -

    -
    -

    O que significam os códigos de saída?

    -

    - Cada término tem seu próprio código, a saída legível por máquina vai para a saída padrão, e uma - execução com falha não imprime nada lá. A tabela é um contrato congelado - mudar o que um código - significa exige uma versão maior. -

    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    CódigoSignificado
    0Tudo funcionou.
    1Um erro inesperado dentro da ferramenta.
    2Comando ou opção incorretos.
    3A receita não é válida.
    4O formato não consegue fazer o que foi pedido.
    5Uma leitura ou escrita falhou.
    6Espaço em disco insuficiente.
    7verify encontrou uma divergência.
    8A execução terminou, mas nem tudo foi produzido.
    130Interrompido com Ctrl+C.
    143Encerrado por um sinal, que é a cara de um timeout de CI.
    -
    -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - Uma execução parada com Ctrl+C ainda deixa um manifesto e nunca deixa um arquivo pela metade, então - um job cancelado ainda pode ser limpo pelo seguinte. -

    -

    - Workflows prontos para GitHub Actions e GitLab CI: como - gerar arquivos de teste em um pipeline de CI. -

    +
    +

    O que a ferramenta faz, por assunto

    +
      +
    • +

      Formatos

      +

      Todos os formatos que o gerador produz, o menor arquivo possível de cada um e as configurações que aceita. Os 32 abrem no programa a que pertencem.

      +
    • +
    • +

      Presets

      +

      Conjuntos prontos de arquivos de teste, cada um responde a uma pergunta: limites de upload, nomes, codificações, importação, arquivos vazios e validação.

      +
    • +
    • +

      Arquivos corrompidos

      +

      Um arquivo quebrado de propósito, com o tamanho exato que você pede e um manifesto dizendo que o seu sistema deve rejeitá-lo. Para testar validação de upload e parsers.

      +
    • +
    • +

      Arquivos de exemplo

      +

      Arquivos de teste para download: um de cada formato com 1 MB, PDF, Word e Excel corrompidos, tabelas CSV e imagens de espaço reservado, cada um com seu SHA-256.

      +
    • +
    • +

      Casos de teste de upload

      +

      Casos de teste de upload de arquivos: limite de tamanho, arquivo vazio e corrompido, tipo errado, nomes inesperados e ZIP, cada um com o arquivo que o testa.

      +
    • +
    • +

      Arquivos de teste no CI

      +

      Gere arquivos de teste no pipeline em vez de commitar binários: workflow do GitHub Actions, job do GitLab, códigos de saída e a pegadinha do PowerShell.

      +
    • +
    • +

      Tamanho exato

      +

      fsutil, dd, truncate e mkfile, cada um medido no seu sistema, e por que um arquivo feito assim não é um PDF nem um PNG quando um teste precisa de um.

      +
    • +
    -
    -

    Existe uma janela de desktop?

    -

    - Sim, o mesmo motor com uma janela por cima, para o teste que não é automatizado. Não é uma versão - reduzida: um teste compara as duas interfaces capacidade por capacidade, e tudo que só uma delas - pode fazer precisa ser declarado e justificado em vez de divergir em silêncio. -

    +
    +

    Ainda com dúvidas?

    - As telas são um lote, presets, vários lotes de uma vez e Sobre. Ela mostra quanto uma execução - custaria antes de escrever qualquer coisa, informa o progresso enquanto roda e pode ser - cancelada no meio sem deixar um arquivo pela metade. Ainda não abre um arquivo de receita - por - enquanto receitas são coisa de linha de comando, e a janela monta seus lotes no formulário. + tfg <command> --help mostra no terminal o que um comando aceita. Cada recusa nomeia a configuração a que se refere, o motivo e um valor que funcionaria. Se algo não se comportar como uma página diz, avise-nos. É um erro da página ou do programa.

    diff --git a/web/public/pt-br/ferramentas/index.html b/web/public/pt-br/ferramentas/index.html index 65cc7ceb..28f73900 100644 --- a/web/public/pt-br/ferramentas/index.html +++ b/web/public/pt-br/ferramentas/index.html @@ -151,6 +151,21 @@
    +

    Documentação

    Checar um arquivo compactado antes de descompactá-lo e conferir somas de verificação

    diff --git a/web/public/recipes/archive-upload.yaml b/web/public/recipes/archive-upload.yaml new file mode 100644 index 00000000..cb926596 --- /dev/null +++ b/web/public/recipes/archive-upload.yaml @@ -0,0 +1,113 @@ +# Archives for testing an upload or an import that unpacks what it is given. +# +# tfg generate archive-upload.yaml +# +# The files and manifest.json land in ./archive-upload. Every entry inside an +# archive is a real file of its format. Run "tfg tool archive-scan" on any of +# them to see what is inside without unpacking it. + +version: 1 +seed: 404 + +targets: + # Ordinary archives: text files and PDF files in a ZIP, and pictures in a + # TAR.GZ, which a form that takes ZIP files may or may not take as well. + - id: texts_zip + format: zip + size: 200kb + name: texts.zip + properties: + entries: 20 + entry_format: txt + entry_size: 8kb + expected: accept + - id: documents_zip + format: zip + size: 2mb + name: documents.zip + properties: + entries: 5 + entry_format: pdf + entry_size: 300kb + compression: default + expected: accept + - id: pictures_targz + format: targz + size: 2mb + name: pictures.tar.gz + properties: + entries: 10 + entry_format: png + entry_size: 100kb + expected: + outcome: unspecified + reason: extension_rule + + # Shapes an unpacker meets less often: many entries, files five folders + # deep, folders listed as entries of their own, and an archive with nothing + # in it. + - id: many_entries + format: zip + size: 20mb + name: many_entries.zip + properties: + entries: 5000 + entry_format: txt + entry_size: 1kb + expected: + outcome: unspecified + reason: count_limit + - id: nested + format: zip + size: 200kb + name: five_folders_deep.zip + properties: + depth: 5 + expected: + outcome: unspecified + reason: nesting_depth + - id: with_folders + format: zip + size: 100kb + name: with_folders.zip + properties: + entries: 4 + depth: 2 + directory_entries: true + expected: accept + # Kept at 1 KB. A larger empty archive needs a filler entry to reach its + # size, and would no longer be empty. + - id: empty_zip + format: zip + size: 1kb + name: empty.zip + properties: + entries: 0 + expected: + outcome: unspecified + reason: count_limit + + # An archive locked with a password, which an unpacker cannot read without + # being given it. The password is test. + - id: encrypted + format: zip + size: 100kb + name: encrypted.zip + properties: + encryption: aes-256 + password: test + expected: unspecified + + # Broken on purpose: a ZIP cut short the way an interrupted upload leaves it. + - id: truncated_zip + format: zip + size: 500kb + name: truncated.zip + damage: + - truncate + expected: + outcome: reject + reason: content_malformed + +output: + dir: ./archive-upload diff --git a/web/public/recipes/bulk-files.yaml b/web/public/recipes/bulk-files.yaml new file mode 100644 index 00000000..e1683edf --- /dev/null +++ b/web/public/recipes/bulk-files.yaml @@ -0,0 +1,22 @@ +# Ten thousand small files, for testing what a system does with many files at +# once: a sync folder, a backup, a file browser, a search index, a batch job. +# +# tfg generate bulk-files.yaml +# +# The files and manifest.json land in ./bulk-files, about 45 MB in all. The +# sizes are drawn from the seed, so the same recipe gives the same set every +# time. Raise the count for a larger set. + +version: 1 +seed: 606 + +targets: + - id: logs + format: log + count: 10000 + size-range: 1kb-8kb + name: log_{index:04}.log + expected: accept + +output: + dir: ./bulk-files diff --git a/web/public/recipes/ci-smoke.yaml b/web/public/recipes/ci-smoke.yaml new file mode 100644 index 00000000..cc8ea166 --- /dev/null +++ b/web/public/recipes/ci-smoke.yaml @@ -0,0 +1,71 @@ +# One small file of each common format, for a quick check in CI that a system +# reads what it should. Runs in a second and writes well under a megabyte. +# +# tfg generate ci-smoke.yaml +# tfg verify ci-smoke/manifest.json +# +# The files and manifest.json land in ./ci-smoke. The same seed gives the same +# bytes on every machine, so the set never has to be committed. + +version: 1 +seed: 505 + +targets: + - id: txt + format: txt + size: 4kb + name: smoke.txt + expected: accept + - id: csv + format: csv + size: 8kb + name: smoke.csv + expected: accept + - id: json + format: json + size: 8kb + name: smoke.json + expected: accept + - id: xml + format: xml + size: 8kb + name: smoke.xml + expected: accept + - id: html + format: html + size: 8kb + name: smoke.html + expected: accept + - id: pdf + format: pdf + size: 16kb + name: smoke.pdf + expected: accept + - id: docx + format: docx + size: 16kb + name: smoke.docx + expected: accept + - id: xlsx + format: xlsx + size: 16kb + name: smoke.xlsx + expected: accept + - id: png + format: png + size: 16kb + name: smoke.png + expected: accept + - id: jpg + format: jpg + size: 16kb + name: smoke.jpg + expected: accept + - id: zip + format: zip + size: 16kb + name: smoke.zip + expected: accept + +output: + dir: ./ci-smoke diff --git a/web/public/recipes/document-upload.yaml b/web/public/recipes/document-upload.yaml new file mode 100644 index 00000000..d40aecfb --- /dev/null +++ b/web/public/recipes/document-upload.yaml @@ -0,0 +1,126 @@ +# Documents for testing a document upload: invoices, CVs, reports, contracts. +# +# tfg generate document-upload.yaml +# +# The files and manifest.json land in ./document-upload. The manifest says +# which files your form should take and which it should turn away. Change the +# limit below to the one your form declares before you run it. + +version: 1 +seed: 202 + +# Seven PDF files around the size limit, from 1 MB under it to 1 MB over, with +# the limit itself among them. They come from the size-boundaries preset. +extends: preset:size-boundaries +with: + limit: 10mb + format: pdf + +targets: + # PDF and Word, which a document form takes, then Excel, PowerPoint, RTF + # and plain text, which some forms refuse. Whether yours does is its + # policy, so those say unspecified: set them to what your form does. + - id: invoice_pdf + format: pdf + size: 300kb + name: invoice.pdf + properties: + pages: 3 + page_size: a4 + expected: accept + - id: letter_pdf + format: pdf + size: 200kb + name: letter_size.pdf + properties: + pages: 2 + page_size: letter + expected: accept + - id: cv_docx + format: docx + size: 200kb + name: cv.docx + properties: + paragraphs: 40 + expected: accept + - id: report_xlsx + format: xlsx + size: 1mb + name: report.xlsx + properties: + rows: 500 + columns: 12 + expected: + outcome: unspecified + reason: extension_rule + - id: slides_pptx + format: pptx + size: 1mb + name: slides.pptx + expected: + outcome: unspecified + reason: extension_rule + - id: notes_rtf + format: rtf + size: 50kb + name: notes.rtf + expected: + outcome: unspecified + reason: extension_rule + - id: notes_txt + format: txt + size: 20kb + name: notes.txt + expected: + outcome: unspecified + reason: extension_rule + + # A long document: 500 pages in one PDF. + - id: long_pdf + format: pdf + size: 5mb + name: long_document.pdf + properties: + pages: 500 + expected: accept + + # Broken documents: a PDF with its first bytes zeroed, and a Word file cut in + # half the way an interrupted upload leaves it. + - id: corrupt_pdf + format: pdf + size: 300kb + name: corrupt.pdf + damage: + - zero-head + expected: + outcome: reject + reason: content_malformed + - id: truncated_docx + format: docx + size: 300kb + name: truncated.docx + damage: + - truncate + expected: + outcome: reject + reason: content_malformed + + # Files that are not what their names say: a spreadsheet named as a PDF, and + # an empty file with a PDF's name. + - id: xlsx_named_pdf + format: xlsx + size: 100kb + name: not_a_document.pdf + expected: + outcome: reject + reason: mime_mismatch + - id: empty_pdf + format: txt + size: 0 + name: empty.pdf + expected: + outcome: reject + reason: size_zero + +output: + dir: ./document-upload diff --git a/web/public/recipes/email-attachments.yaml b/web/public/recipes/email-attachments.yaml new file mode 100644 index 00000000..e859d7b4 --- /dev/null +++ b/web/public/recipes/email-attachments.yaml @@ -0,0 +1,123 @@ +# Email messages for testing a system that reads mail: a support inbox, a mail +# import, an archive, an attachment scanner. +# +# tfg generate email-attachments.yaml +# +# The files and manifest.json land in ./email-attachments. Each .eml file opens +# in a mail program, and every attachment inside it is a real file of its +# format. + +version: 1 +seed: 707 + +targets: + # Plain messages, and one written in HTML with a plain text part beside it. + - id: plain + format: eml + size: 8kb + name: plain.eml + expected: accept + - id: html + format: eml + size: 32kb + name: html_and_text.eml + properties: + body: alternative + expected: accept + + # Attachments: a PDF, several pictures, and one large file. + - id: pdf_attached + format: eml + size: 500kb + name: invoice_attached.eml + properties: + attachments: 1 + attachment_format: pdf + attachment_size: 300kb + expected: accept + - id: pictures_attached + format: eml + size: 1mb + name: five_pictures.eml + properties: + attachments: 5 + attachment_format: jpg + attachment_size: 100kb + expected: accept + - id: large_attachment + format: eml + size: 15mb + name: large_attachment.eml + properties: + attachments: 1 + attachment_format: zip + attachment_size: 10mb + expected: + outcome: unspecified + reason: size_limit + + # A picture shown inside the message rather than attached to it. + - id: inline_picture + format: eml + size: 100kb + name: inline_picture.eml + properties: + body: html + inline: 1 + inline_format: png + inline_size: 40kb + expected: accept + + # Encodings a reader has to get right: quoted-printable and base64 text, a + # message in windows-1250, and headers with words outside ASCII. + - id: quoted_printable + format: eml + size: 16kb + name: quoted_printable.eml + properties: + text_encoding: quoted-printable + charset: utf-8 + expected: accept + - id: base64 + format: eml + size: 16kb + name: base64.eml + properties: + text_encoding: base64 + charset: utf-8 + expected: accept + - id: windows_1250 + format: eml + size: 16kb + name: windows_1250.eml + properties: + text_encoding: 8bit + charset: windows-1250 + expected: accept + - id: encoded_headers + format: eml + size: 16kb + name: encoded_headers.eml + properties: + headers: encoded + expected: accept + + # Unusual shapes: a message sent to a thousand people, and a message + # forwarded inside a message, three deep. + - id: many_recipients + format: eml + size: 100kb + name: thousand_recipients.eml + properties: + recipients: 1000 + expected: accept + - id: forwarded + format: eml + size: 32kb + name: forwarded_3_deep.eml + properties: + message_depth: 3 + expected: accept + +output: + dir: ./email-attachments diff --git a/web/public/recipes/image-upload.yaml b/web/public/recipes/image-upload.yaml new file mode 100644 index 00000000..f1f77ddd --- /dev/null +++ b/web/public/recipes/image-upload.yaml @@ -0,0 +1,122 @@ +# Pictures for testing an image upload: a profile photo, an avatar, a gallery. +# +# tfg generate image-upload.yaml +# +# The files and manifest.json land in ./image-upload. The manifest says which +# files your form should take and which it should turn away. Change the limit +# below to the one your form declares before you run it. + +version: 1 +seed: 101 + +# Seven pictures around the size limit, from 1 MB under it to 1 MB over, with +# the limit itself among them. They come from the size-boundaries preset. +extends: preset:size-boundaries +with: + limit: 5mb + format: jpg + +targets: + # JPEG and PNG, which an image form takes, and WebP and GIF, which some + # forms refuse. Whether yours does is its policy, so those two say + # unspecified: set them to what your form does. + - id: photo_jpg + format: jpg + size: 500kb + name: photo.jpg + expected: accept + - id: screenshot_png + format: png + size: 500kb + name: screenshot.png + expected: accept + - id: picture_webp + format: webp + size: 500kb + name: picture.webp + expected: + outcome: unspecified + reason: extension_rule + - id: picture_gif + format: gif + size: 200kb + name: picture.gif + expected: + outcome: unspecified + reason: extension_rule + + # The sizes in pixels a form may refuse: one pixel, and a picture of 36 + # megapixels. Whether either is welcome is your form's decision. + - id: one_pixel + format: png + size: smallest + name: one_pixel.png + properties: + width: 1 + height: 1 + expected: + outcome: unspecified + reason: dimensions_limit + - id: huge_picture + format: jpg + size: smallest + name: huge_picture.jpg + properties: + width: 6000 + height: 6000 + expected: + outcome: unspecified + reason: dimensions_limit + + # Broken pictures at an ordinary size: the first bytes zeroed, and a PNG + # cut in half the way an interrupted upload leaves it. + - id: corrupt_jpg + format: jpg + size: 300kb + name: corrupt.jpg + damage: + - zero-head + expected: + outcome: reject + reason: content_malformed + - id: truncated_png + format: png + size: 300kb + name: truncated.png + damage: + - truncate + expected: + outcome: reject + reason: content_malformed + + # Files that are not pictures: a PDF with a picture's name, and an empty + # file named like a photo. + - id: pdf_named_jpg + format: pdf + size: 100kb + name: not_a_photo.jpg + expected: + outcome: reject + reason: mime_mismatch + - id: empty_jpg + format: txt + size: 0 + name: empty.jpg + expected: + outcome: reject + reason: size_zero + + # A real picture to upload under a name that climbs out of the upload + # folder. It is written as climbs_out.jpg, and the manifest gives the name + # to send it under in send_as. + - id: climbs_out + format: jpg + size: 100kb + name: climbs_out.jpg + send-as: ../../climbs_out.jpg + expected: + outcome: reject + reason: filename_traversal + +output: + dir: ./image-upload diff --git a/web/public/recipes/index.html b/web/public/recipes/index.html new file mode 100644 index 00000000..b6b9f957 --- /dev/null +++ b/web/public/recipes/index.html @@ -0,0 +1,310 @@ + + + + + + +Test File Recipes to Download - Ready YAML for Uploads, Imports and CI + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

    + +
    + +
    + +

    Recipe gallery

    +

    + Ready recipes for test sets people build again and again. Download one, run it, and change it to fit + your system. Each is a short YAML file with a comment on every part, and each writes into a folder of + its own name, so several can run one after another. +

    + +
    +

    How to use one

    +

    + Download the file, then run tfg generate image-upload.yaml. The files and the manifest + land in ./image-upload. Change a limit, a size or a count in the file, and + tfg validate image-upload.yaml checks it before anything is written. +

    +
    + + + +
    +

    Every preset as a recipe

    +

    + A preset is a recipe with a name. These are the recipes the presets stand for, as + tfg preset eject prints them with their default settings. They name no output folder, so + give them one with --out. Each preset has a page of its own with + what it finds and every setting it takes. +

    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    PresetThe question it answersFilesBytes
    empty-and-minimal.yaml
    Empty and minimal
    Does a file that is valid and as small as the format allows get through?3441 762
    filename-handling.yaml
    File name handling
    Will my system store, show and give back a file name it did not expect?5051 200
    picture-sizes.yaml
    Picture sizes
    Does my system take pictures at the sizes screens and platforms use?214 178 420
    size-boundaries.yaml
    Size boundaries
    Is a size limit enforced exactly where it is declared?773 400 320
    tabular-import.yaml
    Tabular import
    Does my table import survive what real tools export?133 080 060
    text-encoding.yaml
    Text encoding
    Does my reader know which encoding a file is in, or is it guessing?2081 920
    upload-validation.yaml
    Upload validation
    Does my upload form take what it should and turn the rest away?75120 655 872
    +
    +
    tfg generate size-boundaries.yaml --out ./size-boundaries
    +
    + +
    +

    Write your own

    +

    + Every key a recipe takes is in the recipe reference, and every setting of + every format in Format settings. A recipe can also start from a + preset with extends, as the image, document and media recipes here do, and add its own + files after the set of the preset. +

    +
    + +
    + + + + diff --git a/web/public/recipes/media-upload.yaml b/web/public/recipes/media-upload.yaml new file mode 100644 index 00000000..085cc531 --- /dev/null +++ b/web/public/recipes/media-upload.yaml @@ -0,0 +1,98 @@ +# Video and sound for testing a media upload: a video message, a voice note, a +# course platform, a transcoding queue. +# +# tfg generate media-upload.yaml +# +# The files and manifest.json land in ./media-upload. Every file plays in an +# ordinary player. Change the limit below to the one your form declares before +# you run it. + +version: 1 +seed: 808 + +# Seven videos around the size limit, from 1 MB under it to 1 MB over, with the +# limit itself among them. They come from the size-boundaries preset. +extends: preset:size-boundaries +with: + limit: 10mb + format: mp4 + +targets: + # MP4, which a video form takes, then WebM and a WAV voice note, which + # some forms refuse. Whether yours does is its policy, so those two say + # unspecified: set them to what your form does. + - id: video_mp4 + format: mp4 + size: 2mb + name: video.mp4 + properties: + width: 1280 + height: 720 + duration: 5s + expected: accept + - id: video_webm + format: webm + size: 2mb + name: video.webm + properties: + width: 1280 + height: 720 + duration: 5s + expected: + outcome: unspecified + reason: extension_rule + - id: voice_wav + format: wav + size: 1mb + name: voice_note.wav + properties: + sample_rate: 16000 + channels: 1 + expected: + outcome: unspecified + reason: extension_rule + + # Shapes a player or a transcoder meets less often: a portrait phone video, + # ten minutes of video at one frame a second, and sound that is only + # silence. Whether ten minutes is too long is your platform's decision. + - id: portrait + format: mp4 + size: 2mb + name: portrait_phone.mp4 + properties: + width: 720 + height: 1280 + duration: 5s + expected: accept + - id: long_video + format: mp4 + size: 6mb + name: ten_minutes.mp4 + properties: + width: 320 + height: 240 + duration: 10m + frame_rate: 1 + expected: unspecified + - id: silence + format: wav + size: 500kb + name: silence.wav + properties: + content: silence + expected: unspecified + + # Broken on purpose: a video cut short the way an interrupted upload leaves + # it. + - id: truncated_mp4 + format: mp4 + size: 2mb + name: truncated.mp4 + damage: + - truncate + expected: + outcome: reject + reason: content_malformed + +output: + dir: ./media-upload diff --git a/web/public/recipes/presets/empty-and-minimal.yaml b/web/public/recipes/presets/empty-and-minimal.yaml new file mode 100644 index 00000000..d4a6b607 --- /dev/null +++ b/web/public/recipes/presets/empty-and-minimal.yaml @@ -0,0 +1,283 @@ +# Generated by: tfg preset eject empty-and-minimal +# Does a file that is valid and as small as the format allows get through? +# +# Edit it, commit it, it is an ordinary recipe from here on. + +version: 1 +targets: + - id: minimal_avif + format: avif + count: 1 + size: 311 + name: minimal.avif + group: minimal + purpose: "The smallest valid AV1 Image File Format file this build can write. Your system should take it - a refusal means a check on size or type is stricter than the format itself." + expected: accept + - id: minimal_bmp + format: bmp + count: 1 + size: 58 + name: minimal.bmp + group: minimal + purpose: "The smallest valid Windows Bitmap file this build can write. Your system should take it - a refusal means a check on size or type is stricter than the format itself." + expected: accept + - id: minimal_csv + format: csv + count: 1 + size: 115 + name: minimal.csv + group: minimal + purpose: "The smallest valid Comma-Separated Values file this build can write. Your system should take it - a refusal means a check on size or type is stricter than the format itself." + expected: accept + - id: minimal_docx + format: docx + count: 1 + size: 1220 + name: minimal.docx + group: minimal + purpose: "The smallest valid Word (Office Open XML) file this build can write. Your system should take it - a refusal means a check on size or type is stricter than the format itself." + expected: accept + - id: minimal_eml + format: eml + count: 1 + size: 289 + name: minimal.eml + group: minimal + purpose: "The smallest valid Email message file this build can write. Your system should take it - a refusal means a check on size or type is stricter than the format itself." + expected: accept + - id: minimal_geojson + format: geojson + count: 1 + size: 875 + name: minimal.geojson + group: minimal + purpose: "The smallest valid GeoJSON file this build can write. Your system should take it - a refusal means a check on size or type is stricter than the format itself." + expected: accept + - id: minimal_gif + format: gif + count: 1 + size: 114 + name: minimal.gif + group: minimal + purpose: "The smallest valid Graphics Interchange Format file this build can write. Your system should take it - a refusal means a check on size or type is stricter than the format itself." + expected: accept + - id: minimal_html + format: html + count: 1 + size: 122 + name: minimal.html + group: minimal + purpose: "The smallest valid HyperText Markup Language file this build can write. Your system should take it - a refusal means a check on size or type is stricter than the format itself." + expected: accept + - id: minimal_ico + format: ico + count: 1 + size: 70 + name: minimal.ico + group: minimal + purpose: "The smallest valid Windows Icon file this build can write. Your system should take it - a refusal means a check on size or type is stricter than the format itself." + expected: accept + - id: minimal_jpg + format: jpg + count: 1 + size: 602 + name: minimal.jpg + group: minimal + purpose: "The smallest valid JPEG file this build can write. Your system should take it - a refusal means a check on size or type is stricter than the format itself." + expected: accept + - id: minimal_json + format: json + count: 1 + size: 219 + name: minimal.json + group: minimal + purpose: "The smallest valid JavaScript Object Notation file this build can write. Your system should take it - a refusal means a check on size or type is stricter than the format itself." + expected: accept + - id: minimal_jxl + format: jxl + count: 1 + size: 147 + name: minimal.jxl + group: minimal + purpose: "The smallest valid JPEG XL file this build can write. Your system should take it - a refusal means a check on size or type is stricter than the format itself." + expected: accept + - id: minimal_log + format: log + count: 1 + size: 155 + name: minimal.log + group: minimal + purpose: "The smallest valid Server and application log file this build can write. Your system should take it - a refusal means a check on size or type is stricter than the format itself." + expected: accept + - id: minimal_md + format: md + count: 1 + size: 1 + name: minimal.md + group: minimal + purpose: "The smallest valid Markdown file this build can write. Your system should take it - a refusal means a check on size or type is stricter than the format itself." + expected: accept + - id: minimal_mp4 + format: mp4 + count: 1 + size: 3312 + name: minimal.mp4 + group: minimal + purpose: "The smallest valid MP4 video file this build can write. Your system should take it - a refusal means a check on size or type is stricter than the format itself." + expected: accept + - id: minimal_otlp + format: otlp + count: 1 + size: 1266 + name: minimal.jsonl + group: minimal + purpose: "The smallest valid OpenTelemetry Protocol JSON file this build can write. Your system should take it - a refusal means a check on size or type is stricter than the format itself." + expected: accept + - id: minimal_pdf + format: pdf + count: 1 + size: 3415 + name: minimal.pdf + group: minimal + purpose: "The smallest valid Portable Document Format file this build can write. Your system should take it - a refusal means a check on size or type is stricter than the format itself." + expected: accept + - id: minimal_png + format: png + count: 1 + size: 74 + name: minimal.png + group: minimal + purpose: "The smallest valid Portable Network Graphics file this build can write. Your system should take it - a refusal means a check on size or type is stricter than the format itself." + expected: accept + - id: minimal_pptx + format: pptx + count: 1 + size: 4809 + name: minimal.pptx + group: minimal + purpose: "The smallest valid PowerPoint (Office Open XML) file this build can write. Your system should take it - a refusal means a check on size or type is stricter than the format itself." + expected: accept + - id: minimal_rtf + format: rtf + count: 1 + size: 65 + name: minimal.rtf + group: minimal + purpose: "The smallest valid Rich Text Format file this build can write. Your system should take it - a refusal means a check on size or type is stricter than the format itself." + expected: accept + - id: minimal_svg + format: svg + count: 1 + size: 194 + name: minimal.svg + group: minimal + purpose: "The smallest valid Scalable Vector Graphics file this build can write. Your system should take it - a refusal means a check on size or type is stricter than the format itself." + expected: accept + - id: minimal_targz + format: targz + count: 1 + size: 9790 + name: minimal.tar.gz + group: minimal + purpose: "The smallest valid tar + gzip file this build can write. Your system should take it - a refusal means a check on size or type is stricter than the format itself." + expected: accept + - id: minimal_tiff + format: tiff + count: 1 + size: 183 + name: minimal.tiff + group: minimal + purpose: "The smallest valid Tagged Image File Format file this build can write. Your system should take it - a refusal means a check on size or type is stricter than the format itself." + expected: accept + - id: minimal_toml + format: toml + count: 1 + size: 212 + name: minimal.toml + group: minimal + purpose: "The smallest valid TOML file this build can write. Your system should take it - a refusal means a check on size or type is stricter than the format itself." + expected: accept + - id: minimal_txt + format: txt + count: 1 + size: 1 + name: minimal.txt + group: minimal + purpose: "The smallest valid Plain text file this build can write. Your system should take it - a refusal means a check on size or type is stricter than the format itself." + expected: accept + - id: minimal_wav + format: wav + count: 1 + size: 98 + name: minimal.wav + group: minimal + purpose: "The smallest valid Waveform Audio file this build can write. Your system should take it - a refusal means a check on size or type is stricter than the format itself." + expected: accept + - id: minimal_webm + format: webm + count: 1 + size: 3284 + name: minimal.webm + group: minimal + purpose: "The smallest valid WebM video file this build can write. Your system should take it - a refusal means a check on size or type is stricter than the format itself." + expected: accept + - id: minimal_webp + format: webp + count: 1 + size: 148 + name: minimal.webp + group: minimal + purpose: "The smallest valid WebP file this build can write. Your system should take it - a refusal means a check on size or type is stricter than the format itself." + expected: accept + - id: minimal_xlsx + format: xlsx + count: 1 + size: 1726 + name: minimal.xlsx + group: minimal + purpose: "The smallest valid Excel (Office Open XML) file this build can write. Your system should take it - a refusal means a check on size or type is stricter than the format itself." + expected: accept + - id: minimal_xml + format: xml + count: 1 + size: 264 + name: minimal.xml + group: minimal + purpose: "The smallest valid Extensible Markup Language file this build can write. Your system should take it - a refusal means a check on size or type is stricter than the format itself." + expected: accept + - id: minimal_yaml + format: yaml + count: 1 + size: 241 + name: minimal.yaml + group: minimal + purpose: "The smallest valid YAML file this build can write. Your system should take it - a refusal means a check on size or type is stricter than the format itself." + expected: accept + - id: minimal_zip + format: zip + count: 1 + size: 8382 + name: minimal.zip + group: minimal + purpose: "The smallest valid ZIP file this build can write. Your system should take it - a refusal means a check on size or type is stricter than the format itself." + expected: accept + - id: empty_md + format: md + count: 1 + size: 0 + name: empty.md + group: empty + purpose: "An empty Markdown file, nought bytes, which the format allows. Whether your system takes it or turns it away is its own policy - decide which, and check that it does that." + expected: + outcome: unspecified + reason: size_zero + - id: empty_txt + format: txt + count: 1 + size: 0 + name: empty.txt + group: empty + purpose: "An empty Plain text file, nought bytes, which the format allows. Whether your system takes it or turns it away is its own policy - decide which, and check that it does that." + expected: + outcome: unspecified + reason: size_zero diff --git a/web/public/recipes/presets/filename-handling.yaml b/web/public/recipes/presets/filename-handling.yaml new file mode 100644 index 00000000..1904f568 --- /dev/null +++ b/web/public/recipes/presets/filename-handling.yaml @@ -0,0 +1,499 @@ +# Generated by: tfg preset eject filename-handling +# Will my system store, show and give back a file name it did not expect? +# +# Edit it, commit it, it is an ordinary recipe from here on. + +version: 1 +targets: + - id: polish_diacritics + format: txt + count: 1 + size: 1024 + name: zażółć gęślą jaźń.txt + group: scripts + purpose: A Polish name with diacritics, each accented letter two bytes in UTF-8. A system that stores the name in one encoding and shows it in another turns it into mojibake. + expected: + outcome: unspecified + reason: filename_invalid + - id: cyrillic + format: txt + count: 1 + size: 1024 + name: Отчёт за квартал.txt + group: scripts + purpose: A name in Cyrillic, so none of it is ASCII. It shows whether the name survives storage, display and download without turning into question marks. + expected: + outcome: unspecified + reason: filename_invalid + - id: cjk + format: txt + count: 1 + size: 1024 + name: 報告書.txt + group: scripts + purpose: A name in Japanese, three bytes a character in UTF-8. It checks that the name is kept whole and shown in its own script. + expected: + outcome: unspecified + reason: filename_invalid + - id: rtl_with_digits + format: txt + count: 1 + size: 1024 + name: تقرير 2024 v2.txt + group: scripts + purpose: An Arabic word followed by a year and a version, written right to left. A list or a log that ignores the direction of the text shows the parts in the wrong order. + expected: + outcome: unspecified + reason: filename_invalid + - id: emoji + format: txt + count: 1 + size: 1024 + name: 🎉.txt + group: scripts + purpose: "A name that is one emoji - four bytes in UTF-8 and two units in UTF-16. Storage that allows three bytes a character, such as the old utf8 of MySQL, refuses it or cuts it." + expected: + outcome: unspecified + reason: filename_invalid + - id: emoji_zwj + format: txt + count: 1 + size: 1024 + name: "👨\u200d👩\u200d👧 family.txt" + group: scripts + purpose: A family emoji made of three emoji joined by zero width joiners, then a word. Counting characters, cutting or reversing the name breaks the family apart. + expected: + outcome: unspecified + reason: filename_invalid + - id: nfd + format: txt + count: 1 + size: 1024 + name: café.txt + group: scripts + purpose: The word cafe with its accent written as a separate character after the e. It looks like the usual spelling, and a system comparing bytes treats the two as different files. + expected: + outcome: unspecified + reason: filename_invalid + - id: hangul_nfd + format: txt + count: 1 + size: 1024 + name: 한국어 보고서.txt + group: scripts + purpose: A Korean name written as separate letters rather than syllables, the way macOS hands names over. It checks that the name is shown as syllables and matched to its usual spelling. + expected: + outcome: unspecified + reason: filename_invalid + - id: case_mapping + format: txt + count: 1 + size: 1024 + name: İstanbul Straße.txt + group: scripts + purpose: A dotted capital I and a sharp s, whose upper and lower case forms change length or letter. A system that changes case before it compares or stores names gets them wrong. + expected: + outcome: unspecified + reason: filename_invalid + - id: fullwidth + format: txt + count: 1 + size: 1024 + name: report.txt + group: scripts + purpose: The word report in full width letters, which Unicode normalisation turns into ordinary ones. It shows whether a system normalises names and then finds two files under one name. + expected: + outcome: unspecified + reason: filename_invalid + - id: combining_stack + format: txt + count: 1 + size: 1024 + name: z̵̡a̷l̸g̶o.txt + group: scripts + purpose: Letters with several combining marks stacked on each one. It checks that a list or a label keeps the name inside its line and never cuts it in the middle of a letter. + expected: + outcome: unspecified + reason: filename_invalid + - id: bidi_override + format: txt + count: 1 + size: 1024 + name: "photo\u202egpj.txt" + group: lookalike + purpose: A right to left override inside the name, so the file ends in .txt and is shown as if it ended in .jpg. It checks that the system shows the real extension and does not trust what is displayed. + expected: + outcome: unspecified + reason: filename_invalid + - id: zero_width + format: txt + count: 1 + size: 1024 + name: "in\u200bvoice.txt" + group: lookalike + purpose: The word invoice with a zero width space inside it. It looks exactly like invoice, so a system that shows names without marking such characters lets two different names look the same. + expected: + outcome: unspecified + reason: filename_invalid + - id: no_break_space + format: txt + count: 1 + size: 1024 + name: "annual\u00a0report.txt" + group: lookalike + purpose: A no-break space between the two words instead of an ordinary one. It looks the same, and a search, a comparison or a trim that knows only the ordinary space misses it. + expected: + outcome: unspecified + reason: filename_invalid + - id: homoglyph + format: txt + count: 1 + size: 1024 + name: pаypal.txt + group: lookalike + purpose: The word paypal with a Cyrillic a in place of the Latin one. It looks identical, and it checks whether the system warns about names that mix scripts. + expected: + outcome: unspecified + reason: filename_invalid + - id: leading_bom + format: txt + count: 1 + size: 1024 + name: "\ufeffreport.txt" + group: lookalike + purpose: A byte order mark at the start of the name, invisible on screen. A system that strips it from file contents and not from names ends up with a name nobody can type. + expected: + outcome: unspecified + reason: filename_invalid + - id: line_separator + format: txt + count: 1 + size: 1024 + name: "report\u2028ERROR admin logged in.txt" + group: lookalike + purpose: A Unicode line separator in the name, followed by words that read like a log entry. A log that writes names as they are shows a line nobody logged. + expected: + outcome: unspecified + reason: filename_invalid + - id: unicode_tags + format: txt + count: 1 + size: 1024 + name: "report\U000e0068\U000e0069\U000e0064\U000e0064\U000e0065\U000e006e\U000e0020\U000e006e\U000e006f\U000e0074\U000e0065.txt" + group: lookalike + purpose: "The word report followed by invisible Unicode tag characters that spell a short note. The name looks like report, and anything reading the raw name - a script, a language model - sees text a person cannot." + expected: + outcome: unspecified + reason: filename_invalid + - id: leading_space + format: txt + count: 1 + size: 1024 + name: " leading space.txt" + group: spaces-and-dots + purpose: A name that begins with a space. Many systems trim it on the way in or on the way out, and the file can then no longer be found under the name it was given. + expected: + outcome: unspecified + reason: filename_invalid + - id: leading_ideographic_space + format: txt + count: 1 + size: 1024 + name: "\u3000report.txt" + group: spaces-and-dots + purpose: A name that begins with an ideographic space, the wide space of CJK scripts. It checks whether the system keeps it, trims it or shows it, and whether that is what you want. + expected: + outcome: unspecified + reason: filename_invalid + - id: double_space + format: txt + count: 1 + size: 1024 + name: two spaces.txt + group: spaces-and-dots + purpose: Two spaces between the words. A web page shows them as one, so the name on the page is not the name on the disk. + expected: + outcome: unspecified + reason: filename_invalid + - id: leading_dot + format: txt + count: 1 + size: 1024 + name: .hidden.txt + group: spaces-and-dots + purpose: A name that begins with a dot, which Linux and macOS hide from ordinary listings. It checks that the file stays visible and manageable in your system. + expected: + outcome: unspecified + reason: filename_invalid + - id: leading_double_dot + format: txt + count: 1 + size: 1024 + name: ..report.txt + group: spaces-and-dots + purpose: A name that begins with two dots. Code that looks for two dots to stop path traversal may refuse it, and code that strips dots may turn it into another name. + expected: + outcome: unspecified + reason: filename_traversal + - id: only_extension + format: txt + count: 1 + size: 1024 + name: .txt + group: spaces-and-dots + purpose: A name that is only the extension, with nothing before the dot. Linux and macOS hide it, and a system that splits the name at the dot is left with an empty name. + expected: + outcome: unspecified + reason: filename_invalid + - id: many_dots + format: txt + count: 1 + size: 1024 + name: v1.2.3.final.txt + group: spaces-and-dots + purpose: A name with several dots, as in a version number. Only the part after the last dot is the extension, and a system that splits at the first dot gets the type wrong. Your system should take it. + expected: accept + - id: no_extension + format: txt + count: 1 + size: 1024 + name: README + group: spaces-and-dots + purpose: A file called README with no extension at all. A system that requires an extension, or guesses the type from it, has nothing to go on. + expected: + outcome: unspecified + reason: filename_invalid + - id: upper_extension + format: txt + count: 1 + size: 1024 + name: REPORT.TXT + group: spaces-and-dots + purpose: The extension in capitals. A system that compares extensions with case turns away a file it takes in lower case. Your system should take it. + expected: accept + - id: leading_dash + format: txt + count: 1 + size: 1024 + name: -rf.txt + group: metacharacters + purpose: "A name that begins with a dash, -rf. Passed to a command line without a -- before it, it is read as an option." + expected: + outcome: unspecified + reason: filename_invalid + - id: shell_substitution + format: txt + count: 1 + size: 1024 + name: $(id) `id`.txt + group: metacharacters + purpose: A name holding $(id) and the same command in backticks, which a shell runs. It checks that no script or command line ever puts the name into a shell unquoted. + expected: + outcome: unspecified + reason: filename_invalid + - id: shell_separators + format: txt + count: 1 + size: 1024 + name: a;b&c.txt + group: metacharacters + purpose: A name with a semicolon and an ampersand, which end one shell command and start another. It checks that the name never reaches a shell as text. + expected: + outcome: unspecified + reason: filename_invalid + - id: sql_quote + format: txt + count: 1 + size: 1024 + name: "'; DROP TABLE files; --.txt" + group: metacharacters + purpose: A name that closes an SQL string and drops a table. It checks that names go into the database as parameters and are never pasted into a query. + expected: + outcome: unspecified + reason: filename_invalid + - id: script_quote + format: txt + count: 1 + size: 1024 + name: "'-alert(1)-'.txt" + group: metacharacters + purpose: A name that closes a quoted string and calls alert. It checks that a page showing the name escapes it for JavaScript and for HTML. + expected: + outcome: unspecified + reason: filename_invalid + - id: url_encoded_traversal + format: txt + count: 1 + size: 1024 + name: ..%2F..%2Fetc%2Fpasswd.txt + group: metacharacters + purpose: The path ../../etc/passwd with every slash written as %2F. A system that decodes the name after checking it for traversal lets it climb out of the upload directory. + expected: + outcome: unspecified + reason: filename_traversal + - id: fullwidth_traversal + format: txt + count: 1 + size: 1024 + name: ../../etc/passwd.txt + group: metacharacters + purpose: The path ../../etc/passwd in full width dots and slashes, which Unicode normalisation turns into ordinary ones. A system that normalises after checking for traversal lets it climb out of the upload directory. + expected: + outcome: unspecified + reason: filename_traversal + - id: encoded_control + format: txt + count: 1 + size: 1024 + name: report%00%0D%0A.txt + group: metacharacters + purpose: "A name holding %00, %0D and %0A. Decoded, they are a null byte and a line break - a name cut short, or a header or a log line nobody wrote." + expected: + outcome: unspecified + reason: filename_invalid + - id: fullwidth_extension + format: txt + count: 1 + size: 1024 + name: report.txt + group: metacharacters + purpose: The extension in full width letters, so it looks like the real one and is not. A system that normalises before it checks the type sees one extension, and one that does not sees another. + expected: + outcome: unspecified + reason: filename_invalid + - id: url_specials + format: txt + count: 1 + size: 1024 + name: "100% a+b #1.txt" + group: metacharacters + purpose: A name with a percent sign, a plus and a hash. Each means something else in an address, so a download link built without encoding points at another file or cuts the name at the hash. + expected: + outcome: unspecified + reason: filename_invalid + - id: formula + format: txt + count: 1 + size: 1024 + name: =1+1.txt + group: metacharacters + purpose: A name that begins with an equals sign, which a spreadsheet reads as a formula. It checks that a list of names exported to CSV or Excel does not run it. + expected: + outcome: unspecified + reason: filename_invalid + - id: htaccess + format: txt + count: 1 + size: 1024 + name: .htaccess + group: special-names + purpose: A file called .htaccess. On an Apache server that serves the upload directory it changes how the server behaves, whatever the file holds. + expected: + outcome: unspecified + reason: filename_invalid + - id: web_config + format: txt + count: 1 + size: 1024 + name: web.config + group: special-names + purpose: A file called web.config. On an IIS server that serves the upload directory it changes how the server behaves, whatever the file holds. + expected: + outcome: unspecified + reason: filename_invalid + - id: dotenv + format: txt + count: 1 + size: 1024 + name: .env + group: special-names + purpose: A file called .env, the name applications read their settings and secrets from. It checks that an upload cannot land where it would be read as configuration. + expected: + outcome: unspecified + reason: filename_invalid + - id: ds_store + format: txt + count: 1 + size: 1024 + name: .DS_Store + group: special-names + purpose: A file called .DS_Store, which macOS writes into folders. Systems often hide or skip it, and it checks that the file is treated the way you mean. + expected: + outcome: unspecified + reason: filename_invalid + - id: desktop_ini + format: txt + count: 1 + size: 1024 + name: desktop.ini + group: special-names + purpose: A file called desktop.ini, which Windows Explorer reads to decide how a folder looks. It checks that an upload cannot change how a shared folder is shown. + expected: + outcome: unspecified + reason: filename_invalid + - id: office_lock + format: txt + count: 1 + size: 1024 + name: ~$report.txt + group: special-names + purpose: A name that begins with a tilde and a dollar sign, the way Microsoft Office names its lock files. Sync tools and backups often skip such files, so it may quietly not arrive. + expected: + outcome: unspecified + reason: filename_invalid + - id: null_word + format: txt + count: 1 + size: 1024 + name: null.txt + group: values + purpose: "A file called null. A system that turns the name into a value somewhere - JSON, a database, a template - may store no name at all. Your system should take it." + expected: accept + - id: leading_zeros + format: txt + count: 1 + size: 1024 + name: 007.txt + group: values + purpose: A name made of digits with leading zeros. A spreadsheet, a JSON reader or a database column that reads it as a number drops the zeros. Your system should take it. + expected: accept + - id: ustar_101 + format: txt + count: 1 + size: 1024 + name: uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu.txt + group: length + purpose: A name of 101 bytes with its extension, one more than the name field of a ustar tar archive holds. Packing uploads into tar cuts it or moves it into an extra header. + expected: + outcome: unspecified + reason: filename_too_long + - id: max_ascii + format: txt + count: 1 + size: 1024 + name: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.txt + group: length + purpose: A name of 255 bytes in ASCII, the longest most file systems store. A system that adds a prefix or a suffix on the way in pushes it over the limit. + expected: + outcome: unspecified + reason: filename_too_long + - id: cjk_bytes + format: txt + count: 1 + size: 1024 + name: 日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日.txt + group: length + purpose: A name of up to 255 bytes made of CJK characters, three bytes each. A limit counted in characters lets it through where the storage counts bytes. + expected: + outcome: unspecified + reason: filename_too_long + - id: emoji_bytes + format: txt + count: 1 + size: 1024 + name: 🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉.txt + group: length + purpose: A name of up to 255 bytes made of emoji, four bytes and two UTF-16 units each. Characters, bytes and units give three different lengths, and a limit checked with the wrong one lets it through or cuts it. + expected: + outcome: unspecified + reason: filename_too_long diff --git a/web/public/recipes/presets/picture-sizes.yaml b/web/public/recipes/presets/picture-sizes.yaml new file mode 100644 index 00000000..1201b986 --- /dev/null +++ b/web/public/recipes/presets/picture-sizes.yaml @@ -0,0 +1,280 @@ +# Generated by: tfg preset eject picture-sizes +# Does my system take pictures at the sizes screens and platforms use? +# +# Edit it, commit it, it is an ordinary recipe from here on. + +version: 1 +targets: + - id: 1280x720 + format: jpg + count: 1 + size: smallest + name: 1280x720.jpg + group: screens + purpose: A picture of 1280 x 720 written as JPEG, the size of an HD screen. Your system should take it. If it does not, check whether it limits the width, the height or the size of a file below this picture. + expected: + outcome: accept + reason: dimensions_limit + properties: + height: "720" + width: "1280" + - id: 1920x1080 + format: jpg + count: 1 + size: smallest + name: 1920x1080.jpg + group: screens + purpose: A picture of 1920 x 1080 written as JPEG, the size of a Full HD screen. Your system should take it. If it does not, check whether it limits the width, the height or the size of a file below this picture. + expected: + outcome: accept + reason: dimensions_limit + properties: + height: "1080" + width: "1920" + - id: 2560x1440 + format: jpg + count: 1 + size: smallest + name: 2560x1440.jpg + group: screens + purpose: A picture of 2560 x 1440 written as JPEG, the size of a QHD screen and a YouTube channel banner. Your system should take it. If it does not, check whether it limits the width, the height or the size of a file below this picture. + expected: + outcome: accept + reason: dimensions_limit + properties: + height: "1440" + width: "2560" + - id: 3840x2160 + format: jpg + count: 1 + size: smallest + name: 3840x2160.jpg + group: screens + purpose: A picture of 3840 x 2160 written as JPEG, the size of a 4K Ultra HD screen and a YouTube video thumbnail. Your system should take it. If it does not, check whether it limits the width, the height or the size of a file below this picture. + expected: + outcome: accept + reason: dimensions_limit + properties: + height: "2160" + width: "3840" + - id: 98x98 + format: jpg + count: 1 + size: smallest + name: 98x98.jpg + group: avatars + purpose: A picture of 98 x 98 written as JPEG, the size of a YouTube channel picture as YouTube shows it. Your system should take it. If it does not, check whether it limits the width, the height or the size of a file below this picture. + expected: + outcome: accept + reason: dimensions_limit + properties: + height: "98" + width: "98" + - id: 176x176 + format: jpg + count: 1 + size: smallest + name: 176x176.jpg + group: avatars + purpose: A picture of 176 x 176 written as JPEG, the size of a Facebook page picture as a computer shows it. Your system should take it. If it does not, check whether it limits the width, the height or the size of a file below this picture. + expected: + outcome: accept + reason: dimensions_limit + properties: + height: "176" + width: "176" + - id: 196x196 + format: jpg + count: 1 + size: smallest + name: 196x196.jpg + group: avatars + purpose: A picture of 196 x 196 written as JPEG, the size of a Facebook page picture as a phone shows it. Your system should take it. If it does not, check whether it limits the width, the height or the size of a file below this picture. + expected: + outcome: accept + reason: dimensions_limit + properties: + height: "196" + width: "196" + - id: 320x320 + format: jpg + count: 1 + size: smallest + name: 320x320.jpg + group: avatars + purpose: A picture of 320 x 320 written as JPEG, the size of a Facebook page picture as Facebook asks for it. Your system should take it. If it does not, check whether it limits the width, the height or the size of a file below this picture. + expected: + outcome: accept + reason: dimensions_limit + properties: + height: "320" + width: "320" + - id: 400x400 + format: jpg + count: 1 + size: smallest + name: 400x400.jpg + group: avatars + purpose: A picture of 400 x 400 written as JPEG, the size of an X profile photo, the smallest LinkedIn profile photo and a LinkedIn page logo. Your system should take it. If it does not, check whether it limits the width, the height or the size of a file below this picture. + expected: + outcome: accept + reason: dimensions_limit + properties: + height: "400" + width: "400" + - id: 851x315 + format: jpg + count: 1 + size: smallest + name: 851x315.jpg + group: social + purpose: A picture of 851 x 315 written as JPEG, the size of a Facebook page cover. Your system should take it. If it does not, check whether it limits the width, the height or the size of a file below this picture. + expected: + outcome: accept + reason: dimensions_limit + properties: + height: "315" + width: "851" + - id: 1500x500 + format: jpg + count: 1 + size: smallest + name: 1500x500.jpg + group: social + purpose: A picture of 1500 x 500 written as JPEG, the size of an X header. Your system should take it. If it does not, check whether it limits the width, the height or the size of a file below this picture. + expected: + outcome: accept + reason: dimensions_limit + properties: + height: "500" + width: "1500" + - id: 1584x396 + format: jpg + count: 1 + size: smallest + name: 1584x396.jpg + group: social + purpose: A picture of 1584 x 396 written as JPEG, the size of a LinkedIn profile background. Your system should take it. If it does not, check whether it limits the width, the height or the size of a file below this picture. + expected: + outcome: accept + reason: dimensions_limit + properties: + height: "396" + width: "1584" + - id: 2048x1152 + format: jpg + count: 1 + size: smallest + name: 2048x1152.jpg + group: social + purpose: A picture of 2048 x 1152 written as JPEG, the size of the smallest YouTube channel banner. Your system should take it. If it does not, check whether it limits the width, the height or the size of a file below this picture. + expected: + outcome: accept + reason: dimensions_limit + properties: + height: "1152" + width: "2048" + - id: 1200x630 + format: jpg + count: 1 + size: smallest + name: 1200x630.jpg + group: social + purpose: A picture of 1200 x 630 written as JPEG, the size of the picture of a link shared on Facebook. Your system should take it. If it does not, check whether it limits the width, the height or the size of a file below this picture. + expected: + outcome: accept + reason: dimensions_limit + properties: + height: "630" + width: "1200" + - id: 1200x627 + format: jpg + count: 1 + size: smallest + name: 1200x627.jpg + group: social + purpose: A picture of 1200 x 627 written as JPEG, the size of a picture in a LinkedIn post. Your system should take it. If it does not, check whether it limits the width, the height or the size of a file below this picture. + expected: + outcome: accept + reason: dimensions_limit + properties: + height: "627" + width: "1200" + - id: 1080x1080 + format: jpg + count: 1 + size: smallest + name: 1080x1080.jpg + group: social + purpose: A picture of 1080 x 1080 written as JPEG, the size of a square Instagram post. Your system should take it. If it does not, check whether it limits the width, the height or the size of a file below this picture. + expected: + outcome: accept + reason: dimensions_limit + properties: + height: "1080" + width: "1080" + - id: 1080x566 + format: jpg + count: 1 + size: smallest + name: 1080x566.jpg + group: social + purpose: A picture of 1080 x 566 written as JPEG, the size of the widest Instagram post. Your system should take it. If it does not, check whether it limits the width, the height or the size of a file below this picture. + expected: + outcome: accept + reason: dimensions_limit + properties: + height: "566" + width: "1080" + - id: 1080x1440 + format: jpg + count: 1 + size: smallest + name: 1080x1440.jpg + group: social + purpose: A picture of 1080 x 1440 written as JPEG, the size of the tallest Instagram post. Your system should take it. If it does not, check whether it limits the width, the height or the size of a file below this picture. + expected: + outcome: accept + reason: dimensions_limit + properties: + height: "1440" + width: "1080" + - id: 1000x1500 + format: jpg + count: 1 + size: smallest + name: 1000x1500.jpg + group: social + purpose: A picture of 1000 x 1500 written as JPEG, the size of a Pinterest pin. Your system should take it. If it does not, check whether it limits the width, the height or the size of a file below this picture. + expected: + outcome: accept + reason: dimensions_limit + properties: + height: "1500" + width: "1000" + - id: 1080x1920 + format: jpg + count: 1 + size: smallest + name: 1080x1920.jpg + group: social + purpose: A picture of 1080 x 1920 written as JPEG, the size of a Pinterest pin that fills the screen. Your system should take it. If it does not, check whether it limits the width, the height or the size of a file below this picture. + expected: + outcome: accept + reason: dimensions_limit + properties: + height: "1920" + width: "1080" + - id: 2160x3840 + format: jpg + count: 1 + size: smallest + name: 2160x3840.jpg + group: social + purpose: A picture of 2160 x 3840 written as JPEG, the size of a YouTube Shorts thumbnail. Your system should take it. If it does not, check whether it limits the width, the height or the size of a file below this picture. + expected: + outcome: accept + reason: dimensions_limit + properties: + height: "3840" + width: "2160" diff --git a/web/public/recipes/presets/size-boundaries.yaml b/web/public/recipes/presets/size-boundaries.yaml new file mode 100644 index 00000000..a3c14e7d --- /dev/null +++ b/web/public/recipes/presets/size-boundaries.yaml @@ -0,0 +1,69 @@ +# Generated by: tfg preset eject size-boundaries +# Is a size limit enforced exactly where it is declared? +# +# Edit it, commit it, it is an ordinary recipe from here on. + +version: 1 +targets: + - id: under_1mb + format: pdf + count: 1 + size: 9437184 + name: 10mb_under_1mb.pdf + group: size-boundaries + purpose: "A Portable Document Format file 1 048 576 B under the limit of 10mb. Your system should take it - a refusal means the limit is enforced lower than it is declared." + expected: accept + - id: under_1kb + format: pdf + count: 1 + size: 10484736 + name: 10mb_under_1kb.pdf + group: size-boundaries + purpose: "A Portable Document Format file 1 024 B under the limit of 10mb. Your system should take it - a refusal means the limit is enforced lower than it is declared." + expected: accept + - id: under_1b + format: pdf + count: 1 + size: 10485759 + name: 10mb_under_1b.pdf + group: size-boundaries + purpose: "A Portable Document Format file 1 B under the limit of 10mb. Your system should take it - a refusal means the limit is enforced lower than it is declared." + expected: accept + - id: at_limit + format: pdf + count: 1 + size: 10485760 + name: 10mb_at_limit.pdf + group: size-boundaries + purpose: A Portable Document Format file of exactly 10mb, the limit itself. Your system should take it. A refusal here usually means the comparison is off by one, or your system counts a kilobyte as 1000 bytes where this set counts 1024. + expected: accept + - id: over_1b + format: pdf + count: 1 + size: 10485761 + name: 10mb_over_1b.pdf + group: size-boundaries + purpose: "A Portable Document Format file 1 B over the limit of 10mb. Your system should turn it away - taking it means the limit is not enforced, or enforced only in the browser." + expected: + outcome: reject + reason: size_limit + - id: over_1kb + format: pdf + count: 1 + size: 10486784 + name: 10mb_over_1kb.pdf + group: size-boundaries + purpose: "A Portable Document Format file 1 024 B over the limit of 10mb. Your system should turn it away - taking it means the limit is not enforced, or enforced only in the browser." + expected: + outcome: reject + reason: size_limit + - id: over_1mb + format: pdf + count: 1 + size: 11534336 + name: 10mb_over_1mb.pdf + group: size-boundaries + purpose: "A Portable Document Format file 1 048 576 B over the limit of 10mb. Your system should turn it away - taking it means the limit is not enforced, or enforced only in the browser." + expected: + outcome: reject + reason: size_limit diff --git a/web/public/recipes/presets/tabular-import.yaml b/web/public/recipes/presets/tabular-import.yaml new file mode 100644 index 00000000..c254cc38 --- /dev/null +++ b/web/public/recipes/presets/tabular-import.yaml @@ -0,0 +1,172 @@ +# Generated by: tfg preset eject tabular-import +# Does my table import survive what real tools export? +# +# Edit it, commit it, it is an ordinary recipe from here on. + +version: 1 +targets: + - id: dialect_default + format: csv + count: 1 + size: 65536 + name: default.csv + group: csv-dialects + purpose: "The table every other CSV file of this group is compared with, every dialect setting at its default. Your import should take it - if it does not, the fault is not the dialect." + expected: accept + properties: + delimiter: comma + header: "true" + line_ending: lf + quote_style: minimal + - id: dialect_delimiter_pipe + format: csv + count: 1 + size: 65536 + name: delimiter_pipe.csv + group: csv-dialects + purpose: "The default table with delimiter set to pipe and nothing else changed. Whether your import takes this dialect is its own choice - check that it reads the table right or refuses it clearly, and never reads half of it." + expected: + outcome: unspecified + reason: none + properties: + delimiter: pipe + header: "true" + line_ending: lf + quote_style: minimal + - id: dialect_delimiter_semicolon + format: csv + count: 1 + size: 65536 + name: delimiter_semicolon.csv + group: csv-dialects + purpose: "The default table with delimiter set to semicolon and nothing else changed. Whether your import takes this dialect is its own choice - check that it reads the table right or refuses it clearly, and never reads half of it." + expected: + outcome: unspecified + reason: none + properties: + delimiter: semicolon + header: "true" + line_ending: lf + quote_style: minimal + - id: dialect_delimiter_tab + format: csv + count: 1 + size: 65536 + name: delimiter_tab.csv + group: csv-dialects + purpose: "The default table with delimiter set to tab and nothing else changed. Whether your import takes this dialect is its own choice - check that it reads the table right or refuses it clearly, and never reads half of it." + expected: + outcome: unspecified + reason: none + properties: + delimiter: tab + header: "true" + line_ending: lf + quote_style: minimal + - id: dialect_line_ending_crlf + format: csv + count: 1 + size: 65536 + name: line_ending_crlf.csv + group: csv-dialects + purpose: The default table with line_ending set to crlf and nothing else changed. Every CSV reader has to cope with it, so a failure here is a fault in the import rather than a choice. + expected: accept + properties: + delimiter: comma + header: "true" + line_ending: crlf + quote_style: minimal + - id: dialect_header_false + format: csv + count: 1 + size: 65536 + name: header_false.csv + group: csv-dialects + purpose: "The default table with header set to false and nothing else changed. Whether your import takes this dialect is its own choice - check that it reads the table right or refuses it clearly, and never reads half of it." + expected: + outcome: unspecified + reason: none + properties: + delimiter: comma + header: "false" + line_ending: lf + quote_style: minimal + - id: dialect_quote_style_all + format: csv + count: 1 + size: 65536 + name: quote_style_all.csv + group: csv-dialects + purpose: The default table with quote_style set to all and nothing else changed. Every CSV reader has to cope with it, so a failure here is a fault in the import rather than a choice. + expected: accept + properties: + delimiter: comma + header: "true" + line_ending: lf + quote_style: all + - id: dialect_quote_style_none + format: csv + count: 1 + size: 65536 + name: quote_style_none.csv + group: csv-dialects + purpose: The default table with quote_style set to none and nothing else changed. Every CSV reader has to cope with it, so a failure here is a fault in the import rather than a choice. + expected: accept + properties: + delimiter: comma + header: "true" + line_ending: lf + quote_style: none + - id: wide_table + format: csv + count: 1 + size: 709793 + name: wide.csv + group: csv-wide + purpose: "A CSV table with 32768 columns, the most this build writes. A spreadsheet may show only the first 16384 and drop the rest without a word - whether your import refuses such a table, cuts it or takes it whole is its own policy." + expected: + outcome: unspecified + reason: count_limit + properties: + columns: "32768" + - id: sheet + format: xlsx + count: 1 + size: 1649371 + name: sheet.xlsx + group: xlsx-rows + purpose: "An Excel workbook of 1000 rows and 10 columns, as many as were asked for. Your import should take it whole - it checks that a real spreadsheet of this size is read to its last row." + expected: accept + properties: + columns: "10" + rows: "1000" + - id: layout_indented + format: json + count: 1 + size: 65536 + name: indented.json + group: json-layouts + purpose: "The records as JSON, indented across many lines. Every JSON reader takes it - it checks that the import reads the document as JSON rather than line by line." + expected: accept + properties: + formatting: indented + - id: layout_minified + format: json + count: 1 + size: 65536 + name: minified.json + group: json-layouts + purpose: "The records as JSON on one line, with no newline at the end. Every JSON reader takes it - it checks that nothing around the parser, such as a line reader or a log, chokes on one very long line." + expected: accept + properties: + formatting: minified + - id: layout_record_per_line + format: json + count: 1 + size: 65536 + name: record-per-line.json + group: json-layouts + purpose: "The records as JSON with one record on each line. Every JSON reader takes it - it checks that the import does not treat each line as a document of its own." + expected: accept + properties: + formatting: record-per-line diff --git a/web/public/recipes/presets/text-encoding.yaml b/web/public/recipes/presets/text-encoding.yaml new file mode 100644 index 00000000..80b196e9 --- /dev/null +++ b/web/public/recipes/presets/text-encoding.yaml @@ -0,0 +1,243 @@ +# Generated by: tfg preset eject text-encoding +# Does my reader know which encoding a file is in, or is it guessing? +# +# Edit it, commit it, it is an ordinary recipe from here on. + +version: 1 +targets: + - id: encoding_md_utf-16be + format: md + count: 1 + size: 4096 + name: utf-16be.md + group: encoding + purpose: "A Markdown file in UTF-16BE with no byte order mark, two bytes for every character. Whether your reader takes UTF-16 at all is its own policy - check that it reads the text right or refuses it clearly, and never shows it as one character in three." + expected: + outcome: unspecified + reason: encoding_invalid + properties: + bom: "false" + encoding: utf-16be + - id: encoding_md_utf-16be_bom + format: md + count: 1 + size: 4096 + name: utf-16be_bom.md + group: encoding + purpose: "A Markdown file in UTF-16BE that starts with a byte order mark, two bytes for every character. Whether your reader takes UTF-16 at all is its own policy - check that it reads the text right or refuses it clearly, and never shows it as one character in three." + expected: + outcome: unspecified + reason: encoding_invalid + properties: + bom: "true" + encoding: utf-16be + - id: encoding_md_utf-16le + format: md + count: 1 + size: 4096 + name: utf-16le.md + group: encoding + purpose: "A Markdown file in UTF-16LE with no byte order mark, two bytes for every character. Whether your reader takes UTF-16 at all is its own policy - check that it reads the text right or refuses it clearly, and never shows it as one character in three." + expected: + outcome: unspecified + reason: encoding_invalid + properties: + bom: "false" + encoding: utf-16le + - id: encoding_md_utf-16le_bom + format: md + count: 1 + size: 4096 + name: utf-16le_bom.md + group: encoding + purpose: "A Markdown file in UTF-16LE that starts with a byte order mark, two bytes for every character. Whether your reader takes UTF-16 at all is its own policy - check that it reads the text right or refuses it clearly, and never shows it as one character in three." + expected: + outcome: unspecified + reason: encoding_invalid + properties: + bom: "true" + encoding: utf-16le + - id: encoding_md_utf-8 + format: md + count: 1 + size: 4096 + name: utf-8.md + group: encoding + purpose: A Markdown file in UTF-8 with no byte order mark. Your reader should take it and show every character right. + expected: accept + properties: + bom: "false" + encoding: utf-8 + - id: encoding_md_utf-8_bom + format: md + count: 1 + size: 4096 + name: utf-8_bom.md + group: encoding + purpose: "A Markdown file in UTF-8 that starts with a byte order mark. Your reader should take it - the mark is legal, and one shown as three stray characters, or carried into the first field of an import, is a fault." + expected: accept + properties: + bom: "true" + encoding: utf-8 + - id: encoding_txt_utf-16be + format: txt + count: 1 + size: 4096 + name: utf-16be.txt + group: encoding + purpose: "A Plain text file in UTF-16BE with no byte order mark, two bytes for every character. Whether your reader takes UTF-16 at all is its own policy - check that it reads the text right or refuses it clearly, and never shows it as one character in three." + expected: + outcome: unspecified + reason: encoding_invalid + properties: + bom: "false" + encoding: utf-16be + - id: encoding_txt_utf-16be_bom + format: txt + count: 1 + size: 4096 + name: utf-16be_bom.txt + group: encoding + purpose: "A Plain text file in UTF-16BE that starts with a byte order mark, two bytes for every character. Whether your reader takes UTF-16 at all is its own policy - check that it reads the text right or refuses it clearly, and never shows it as one character in three." + expected: + outcome: unspecified + reason: encoding_invalid + properties: + bom: "true" + encoding: utf-16be + - id: encoding_txt_utf-16le + format: txt + count: 1 + size: 4096 + name: utf-16le.txt + group: encoding + purpose: "A Plain text file in UTF-16LE with no byte order mark, two bytes for every character. Whether your reader takes UTF-16 at all is its own policy - check that it reads the text right or refuses it clearly, and never shows it as one character in three." + expected: + outcome: unspecified + reason: encoding_invalid + properties: + bom: "false" + encoding: utf-16le + - id: encoding_txt_utf-16le_bom + format: txt + count: 1 + size: 4096 + name: utf-16le_bom.txt + group: encoding + purpose: "A Plain text file in UTF-16LE that starts with a byte order mark, two bytes for every character. Whether your reader takes UTF-16 at all is its own policy - check that it reads the text right or refuses it clearly, and never shows it as one character in three." + expected: + outcome: unspecified + reason: encoding_invalid + properties: + bom: "true" + encoding: utf-16le + - id: encoding_txt_utf-8 + format: txt + count: 1 + size: 4096 + name: utf-8.txt + group: encoding + purpose: A Plain text file in UTF-8 with no byte order mark. Your reader should take it and show every character right. + expected: accept + properties: + bom: "false" + encoding: utf-8 + - id: encoding_txt_utf-8_bom + format: txt + count: 1 + size: 4096 + name: utf-8_bom.txt + group: encoding + purpose: "A Plain text file in UTF-8 that starts with a byte order mark. Your reader should take it - the mark is legal, and one shown as three stray characters, or carried into the first field of an import, is a fault." + expected: accept + properties: + bom: "true" + encoding: utf-8 + - id: encoding_xml_utf-16be_bom + format: xml + count: 1 + size: 4096 + name: utf-16be_bom.xml + group: encoding + purpose: "A Extensible Markup Language file in UTF-16BE that starts with a byte order mark, two bytes for every character. Whether your reader takes UTF-16 at all is its own policy - check that it reads the text right or refuses it clearly, and never shows it as one character in three." + expected: + outcome: unspecified + reason: encoding_invalid + properties: + bom: "true" + encoding: utf-16be + - id: encoding_xml_utf-16le_bom + format: xml + count: 1 + size: 4096 + name: utf-16le_bom.xml + group: encoding + purpose: "A Extensible Markup Language file in UTF-16LE that starts with a byte order mark, two bytes for every character. Whether your reader takes UTF-16 at all is its own policy - check that it reads the text right or refuses it clearly, and never shows it as one character in three." + expected: + outcome: unspecified + reason: encoding_invalid + properties: + bom: "true" + encoding: utf-16le + - id: encoding_xml_utf-8 + format: xml + count: 1 + size: 4096 + name: utf-8.xml + group: encoding + purpose: A Extensible Markup Language file in UTF-8 with no byte order mark. Your reader should take it and show every character right. + expected: accept + properties: + bom: "false" + encoding: utf-8 + - id: encoding_xml_utf-8_bom + format: xml + count: 1 + size: 4096 + name: utf-8_bom.xml + group: encoding + purpose: "A Extensible Markup Language file in UTF-8 that starts with a byte order mark. Your reader should take it - the mark is legal, and one shown as three stray characters, or carried into the first field of an import, is a fault." + expected: accept + properties: + bom: "true" + encoding: utf-8 + - id: line_endings_csv_crlf + format: csv + count: 1 + size: 4096 + name: crlf.csv + group: line-endings + purpose: "A Comma-Separated Values file whose lines end in CR LF, the way Windows and Excel write them. Your reader should take it - one that splits lines on LF alone keeps a carriage return at the end of every line." + expected: accept + properties: + line_ending: crlf + - id: line_endings_csv_lf + format: csv + count: 1 + size: 4096 + name: lf.csv + group: line-endings + purpose: "A Comma-Separated Values file whose lines end in LF. Your reader should take it - both endings are legal, and a reader that expects the other one sees a single long line or an empty one after each." + expected: accept + properties: + line_ending: lf + - id: line_endings_log_crlf + format: log + count: 1 + size: 4096 + name: crlf.log + group: line-endings + purpose: "A Server and application log file whose lines end in CR LF, the way Windows and Excel write them. Your reader should take it - one that splits lines on LF alone keeps a carriage return at the end of every line." + expected: accept + properties: + line_ending: crlf + - id: line_endings_log_lf + format: log + count: 1 + size: 4096 + name: lf.log + group: line-endings + purpose: "A Server and application log file whose lines end in LF. Your reader should take it - both endings are legal, and a reader that expects the other one sees a single long line or an empty one after each." + expected: accept + properties: + line_ending: lf diff --git a/web/public/recipes/presets/upload-validation.yaml b/web/public/recipes/presets/upload-validation.yaml new file mode 100644 index 00000000..2d5e4ab3 --- /dev/null +++ b/web/public/recipes/presets/upload-validation.yaml @@ -0,0 +1,257 @@ +# Generated by: tfg preset eject upload-validation +# Does my upload form take what it should and turn the rest away? +# +# Edit it, commit it, it is an ordinary recipe from here on. + +version: 1 +targets: + - id: under_1b + format: jpg + count: 1 + size: 10485759 + name: 10mb_under_1b.jpg + group: size-limit + purpose: "A JPEG file 1 B under the limit of 10mb. Your system should take it - a refusal means the limit is enforced lower than it is declared." + expected: accept + - id: at_limit + format: jpg + count: 1 + size: 10485760 + name: 10mb_at_limit.jpg + group: size-limit + purpose: A JPEG file of exactly 10mb, the limit itself. Your system should take it. A refusal here usually means the comparison is off by one, or your system counts a kilobyte as 1000 bytes where this set counts 1024. + expected: accept + - id: over_1b + format: jpg + count: 1 + size: 10485761 + name: 10mb_over_1b.jpg + group: size-limit + purpose: "A JPEG file 1 B over the limit of 10mb. Your system should turn it away - taking it means the limit is not enforced, or enforced only in the browser." + expected: + outcome: reject + reason: size_limit + - id: far_over_2x + format: jpg + count: 1 + size: 20971520 + name: 10mb_far_over_2x.jpg + group: size-limit + purpose: "A JPEG file 2 times the limit of 10mb. Your form should turn it away before it has read the whole of it - one that reads the body into memory first shows it here." + expected: + outcome: reject + reason: size_limit + - id: empty + format: txt + count: 1 + size: 0 + name: empty.jpg + group: degenerate + purpose: "An empty file, nought bytes, under a name your form accepts - somebody pressed upload on nothing. Whether your form takes it or turns it away is its own policy - decide which, and check that it does that." + expected: + outcome: unspecified + reason: size_zero + - id: allowed_jpg + format: jpg + count: 1 + size: 5242880 + name: allowed_jpg.jpg + group: allowed-types + purpose: "A real JPEG file well inside the limit, of a type your form accepts. Your form should take it - if it does not, every refusal in the rest of the set means nothing." + expected: accept + - id: allowed_pdf + format: pdf + count: 1 + size: 5242880 + name: allowed_pdf.pdf + group: allowed-types + purpose: "A real Portable Document Format file well inside the limit, of a type your form accepts. Your form should take it - if it does not, every refusal in the rest of the set means nothing." + expected: accept + - id: allowed_png + format: png + count: 1 + size: 5242880 + name: allowed_png.png + group: allowed-types + purpose: "A real Portable Network Graphics file well inside the limit, of a type your form accepts. Your form should take it - if it does not, every refusal in the rest of the set means nothing." + expected: accept + - id: denied_exe + format: txt + count: 1 + size: 4096 + name: denied.exe + group: denied-types + purpose: A file ending in .exe, an extension your form turns away. It should be refused by its name, whatever it holds. This build has no format of that name, so the file holds plain text. + expected: + outcome: reject + reason: extension_rule + - id: denied_html + format: html + count: 1 + size: 4096 + name: denied.html + group: denied-types + purpose: A file ending in .html, an extension your form turns away. It should be refused by its name, whatever it holds. + expected: + outcome: reject + reason: extension_rule + - id: denied_sh + format: txt + count: 1 + size: 4096 + name: denied.sh + group: denied-types + purpose: A file ending in .sh, an extension your form turns away. It should be refused by its name, whatever it holds. This build has no format of that name, so the file holds plain text. + expected: + outcome: reject + reason: extension_rule + - id: denied_svg + format: svg + count: 1 + size: 4096 + name: denied.svg + group: denied-types + purpose: A file ending in .svg, an extension your form turns away. It should be refused by its name, whatever it holds. + expected: + outcome: reject + reason: extension_rule + - id: mismatch_jpg + format: pdf + count: 1 + size: 4096 + name: pdf_as_jpg.jpg + group: extension-content-mismatch + purpose: "A real Portable Document Format file under a name ending in .jpg. Your form takes both types and should still refuse this one - a form that checks only the extension, and never looks inside, takes it." + expected: + outcome: reject + reason: mime_mismatch + - id: mismatch_pdf + format: png + count: 1 + size: 4096 + name: png_as_pdf.pdf + group: extension-content-mismatch + purpose: "A real Portable Network Graphics file under a name ending in .pdf. Your form takes both types and should still refuse this one - a form that checks only the extension, and never looks inside, takes it." + expected: + outcome: reject + reason: mime_mismatch + - id: mismatch_png + format: jpg + count: 1 + size: 4096 + name: jpg_as_png.png + group: extension-content-mismatch + purpose: "A real JPEG file under a name ending in .png. Your form takes both types and should still refuse this one - a form that checks only the extension, and never looks inside, takes it." + expected: + outcome: reject + reason: mime_mismatch + - id: no_extension + format: jpg + count: 1 + size: 4096 + name: invoice + group: extension-anomalies + purpose: "A file of a type your form accepts, named invoice with no extension at all. Whether your form insists on an extension is its own rule - check that it gives the answer you meant." + expected: + outcome: unspecified + reason: extension_rule + - id: uppercase_extension + format: jpg + count: 1 + size: 4096 + name: PHOTO.JPG + group: extension-anomalies + purpose: "A file of a type your form accepts, with the name and the extension in capitals. A form that compares extensions with case turns it away where it takes the same file in lower case - decide which you want." + expected: + outcome: unspecified + reason: extension_rule + - id: double_extension + format: jpg + count: 1 + size: 4096 + name: invoice.jpg.exe + group: extension-anomalies + purpose: "An allowed extension followed by a denied one. Your form should turn it away - one that looks for an allowed extension anywhere in the name takes it, and a server may then run it." + expected: + outcome: reject + reason: extension_rule + - id: long_name + format: jpg + count: 1 + size: 4096 + name: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.jpg + group: hostile-names + purpose: "A name of 204 letters and the extension. A database column or a path limit shorter than that cuts it or refuses it - check which, and that the file is never stored under a shortened name without a word." + expected: + outcome: unspecified + reason: filename_too_long + - id: outside_ascii + format: jpg + count: 1 + size: 4096 + name: wiadomość_日本語_🎉.jpg + group: hostile-names + purpose: A name with Polish letters, Japanese and an emoji. A form that handles names as bytes, or in a single encoding, stores or shows it garbled. + expected: + outcome: unspecified + reason: filename_invalid + - id: spaces_and_brackets + format: jpg + count: 1 + size: 4096 + name: my report (final) v2.jpg + group: hostile-names + purpose: "A name with spaces and brackets, legal on every system. Your form should take it - a script that does not quote names breaks on it." + expected: accept + - id: bulk + format: jpg + count: 50 + size: 1048576 + name: bulk_{index:04}.jpg + group: bulk-upload + purpose: "50 files of a type your form accepts, uploaded together. Your form should take every one of them - the set checks a limit on how many files arrive at once, and that none of them is lost." + expected: accept + - id: climbing_name + format: jpg + count: 1 + size: 4096 + name: climbing_name.jpg + send-as: ../tfg_climbed_out.jpg + group: hostile-names + purpose: A name that steps one directory up, written with a forward slash. A form that joins the name to its upload directory writes the file outside it. Your form should turn the name away or store the file under a name with no path in it. Then check that no file called tfg_climbed_out.jpg appeared above the upload directory. + expected: + outcome: unspecified + reason: filename_traversal + - id: climbing_name_backslash + format: jpg + count: 1 + size: 4096 + name: climbing_name_backslash.jpg + send-as: "..\\tfg_climbed_out.jpg" + group: hostile-names + purpose: The same step up written with a backslash, which only Windows reads as a separator. A check made on Linux lets the name through whole, and a Windows machine that stores the file later steps out. Your form should turn the name away or store the file under a name with no path in it. Then check that no file called tfg_climbed_out.jpg appeared above the upload directory. + expected: + outcome: unspecified + reason: filename_traversal + - id: absolute_name + format: jpg + count: 1 + size: 4096 + name: absolute_name.jpg + send-as: /tmp/tfg_climbed_out.jpg + group: hostile-names + purpose: A name that is a whole path on Linux and macOS, starting at the root of the disk. A form that uses it as given writes to /tmp. Your form should turn the name away or store the file under a name with no path in it. Then check that /tmp holds no file called tfg_climbed_out.jpg. + expected: + outcome: unspecified + reason: filename_traversal + - id: drive_name + format: jpg + count: 1 + size: 4096 + name: drive_name.jpg + send-as: "C:\\Windows\\Temp\\tfg_climbed_out.jpg" + group: hostile-names + purpose: A name that is a whole path on Windows, drive letter included. A form that uses it as given writes to that folder. Your form should turn the name away or store the file under a name with no path in it. Then check that the folder holds no file called tfg_climbed_out.jpg. + expected: + outcome: unspecified + reason: filename_traversal diff --git a/web/public/recipes/spreadsheet-import.yaml b/web/public/recipes/spreadsheet-import.yaml new file mode 100644 index 00000000..a2c5afe1 --- /dev/null +++ b/web/public/recipes/spreadsheet-import.yaml @@ -0,0 +1,130 @@ +# Tables for testing an import: a CSV or Excel upload, a bulk import screen, a +# data pipeline that reads files. +# +# tfg generate spreadsheet-import.yaml +# +# The files and manifest.json land in ./spreadsheet-import. Every file here is +# a well formed table. The ones marked accept are what most tools export, and +# an importer should take them. The others are shapes and sizes an importer may +# refuse on purpose, so they say unspecified: set them to what your importer +# does. The two at the end are broken on purpose. + +version: 1 +seed: 303 + +targets: + # The same table written the ways real tools export it. + - id: comma_lf + format: csv + size: 50kb + name: comma_lf.csv + expected: accept + - id: comma_crlf + format: csv + size: 50kb + name: comma_crlf.csv + properties: + line_ending: crlf + expected: accept + - id: semicolon + format: csv + size: 50kb + name: semicolon.csv + properties: + delimiter: semicolon + expected: + outcome: unspecified + reason: none + - id: tab + format: csv + size: 50kb + name: tab_separated.csv + properties: + delimiter: tab + expected: + outcome: unspecified + reason: none + - id: no_header + format: csv + size: 50kb + name: no_header.csv + properties: + header: false + expected: + outcome: unspecified + reason: none + - id: every_field_quoted + format: csv + size: 50kb + name: every_field_quoted.csv + properties: + quote_style: all + expected: accept + + # Shapes an importer meets less often: a wide table and a large one. + - id: wide + format: csv + size: 500kb + name: wide_200_columns.csv + properties: + columns: 200 + expected: + outcome: unspecified + reason: count_limit + - id: large + format: csv + size: 20mb + name: large.csv + expected: + outcome: unspecified + reason: size_limit + + # Excel files: a small sheet, a long one and a single cell. + - id: sheet + format: xlsx + size: 2mb + name: sheet.xlsx + properties: + rows: 1000 + columns: 10 + expected: accept + - id: long_sheet + format: xlsx + size: 12mb + name: long_sheet.xlsx + properties: + rows: 10000 + columns: 6 + expected: + outcome: unspecified + reason: count_limit + - id: one_cell + format: xlsx + size: 8kb + name: one_cell.xlsx + properties: + rows: 1 + columns: 1 + expected: accept + + # Broken on purpose: an Excel file cut short, and an empty file named as a + # CSV. + - id: truncated_xlsx + format: xlsx + size: 200kb + name: truncated.xlsx + damage: + - truncate + expected: + outcome: reject + reason: content_malformed + - id: empty_csv + format: txt + size: 0 + name: empty.csv + expected: + outcome: reject + reason: size_zero + +output: + dir: ./spreadsheet-import diff --git a/web/public/ro/documentatie/index.html b/web/public/ro/documentatie/index.html index 4fab5575..84adfef0 100644 --- a/web/public/ro/documentatie/index.html +++ b/web/public/ro/documentatie/index.html @@ -147,389 +147,93 @@

    Documentație

    - Tot ce face instrumentul, aranjat ca întrebările cu care vin oamenii de fapt. - README-ul din repository este referința completă și se potrivește - mereu cu versiunea pe care ai descărcat-o. + Cum instalați tfg, cum faceți primele fișiere de test și tot ce primește și scrie programul: fiecare comandă și fiecare opțiune, fiecare cheie a unei rețete, fiecare câmp al manifestului și fiecare setare a fiecărui format. Aceste pagini sunt în engleză, pentru că sunt produse chiar de program la fiecare construire a site-ului și spun mereu ce face versiunea pe care o descărcați.

    -
    -

    Ce comenzi există?

    -

    Fiecare face un singur lucru:

    -
    tfg generate    produce fișiere, dintr-o rețetă sau din opțiuni
    -tfg validate    verifică o rețetă fără a scrie nimic
    -tfg verify      verifică un director față de un manifest
    -tfg cleanup     șterge fișierele pe care le listează un manifest
    -tfg recipe fmt  afișează o rețetă în forma ei normalizată
    -tfg preset      construiește un set de fișiere dintr-o întrebare de test cu nume
    -tfg formats     listează formatele acceptate de această versiune
    -tfg damage      listează modurile în care această versiune poate strica un fișier intenționat
    -tfg tool        mici unelte pentru fișiere pe care le ai deja
    -tfg version     afișează versiunea instrumentului
    -tfg license     afișează licența și ce înseamnă ea pentru fișierele generate
    -

    - tfg tool cuprinde instrumentele pentru fișiere pe care le ai deja, de exemplu verificarea - unei arhive înainte de dezarhivare. Instrumente descrie fiecare dintre - ele. -

    -
    - -
    -

    Cum generez un singur fișier de dimensiune exactă?

    -

    - Spune formatul, dimensiunea și unde merge. Dimensiunile se numără din 1024 în 1024, deci - 2mb sunt 2097152 octeți. Merge și un simplu număr de octeți, deci --size - 10485761 cere exact atât. -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    Opțiunile utile ale comenzii generate:

    -
    - - - - - - - - - - - - - - - - - -
    OpțiuneCe face
    --format <id>formatul fișierelor, de exemplu txt
    --size <size>dimensiunea exactă a fiecărui fișier, precum 10mb sau un simplu număr de octeți
    --size-range <a-b>o dimensiune extrasă pentru fiecare fișier dintr-un interval, precum 1kb-8kb. Extragerea vine din seed
    --boundary <size>trei fișiere în jurul unei limite: un octet sub, limita, un octet peste
    --count <n>câte fișiere să producă. Implicit 1
    --name <template>șablon de nume, de exemplu invoice_{index:04}.txt
    --out <dir>directorul în care se scrie
    --seed <n>seed-ul rulării. Același seed dă aceiași octeți
    --set <k>=<v>o setare de format, repetabilă
    --damage <name>strică fișierele intenționat, repetabil și aplicat în ordine. Rulează tfg damage pentru listă
    --expected <outcome>accept, reject, sanitize sau unspecified
    --dry-runnumără și arată, nu scrie absolut nimic
    --jsonscrie manifestul la ieșirea standard
    -
    -
    - -
    -

    Cum fac un fișier stricat intenționat?

    -

    - Orice alt fișier scris de acest instrument este corect prin construcție, ceea ce răspunde la două - din cele trei întrebări pe care le pune un validator de încărcare. --damage - răspunde la a treia - se deschide oare fișierul. Fișierul este produs normal și apoi stricat, - deci are în continuare dimensiunea cerută. -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - Setările se pun după două puncte. Opțiunea se repetă, iar ordinea în care le scrii este ordinea în - care se aplică. tfg damage listează ce poate face această versiune și ce acceptă - fiecare. -

    -

    Într-o rețetă cheia este o listă, de nume sau de setări:

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - Un fișier deteriorat primește expected: reject în manifest, cu deteriorarea consemnată - alături. Două lucruri sunt refuzate înainte de a se scrie ceva, pentru că fiecare ar pune pe - disc un fișier pe care manifestul îl descrie greșit: -

    -
      -
    • un fișier mai mic decât are nevoie deteriorarea, pentru că ar ieși neschimbat
    • -
    • - expected: accept alături de o deteriorare, pentru că nimic nu l-ar putea îndeplini. - Scrie sanitize dacă sistemul testat trebuie să repare fișierul sau - unspecified dacă exact asta e întrebarea pe care o pui -
    • -
    -

    - O a treia nu se poate ști dinainte. Dacă o deteriorare rulează și nu mută niciun octet, fișierul - respectiv este abandonat în loc să fie scris - rularea continuă, spune care a fost fișierul și - se termină cu codul de ieșire parțial. -

    -

    - Pas cu pas, cu un test care citește manifestul: cum faci un - fișier corupt pentru teste. -

    -
    - -
    -

    Cum arată o rețetă?

    -

    - O rețetă este un fișier YAML care descrie o rulare întreagă. Comite-o lângă testele tale și - fixture-urile nu mai sunt binare în repository - oricine le poate reconstrui, octet cu octet, - dintr-un fișier de câteva sute de caractere. -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - Fiecare target are nevoie de exact una dintre cheile size, size-range, - boundary sau contains. Două este o eroare și la fel niciuna. O rețetă - invalidă nu scrie niciun fișier și raportează toate problemele deodată, nu doar - prima, fiecare numind setarea la care se referă. -

    -
    - -
    -

    Cum declar ce trebuie să facă sistemul meu cu un fișier?

    -

    Formă scurtă când rezultatul e de ajuns, formă lungă când contează motivul:

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - Rezultatele sunt accept, reject, sanitize și - unspecified. Motivele sunt o listă închisă ca un raport să poată grupa după ele: - content_malformed, count_limit, dimensions_limit, - duplicate, encoding_invalid, extension_rule, - filename_invalid, filename_too_long, filename_traversal, - malware_signature, mime_mismatch, nesting_depth, - none, size_limit și size_zero. -

    -

    - Un motiv numește regula în joc, nu verdictul. De aceea același motiv poate sta sub - oricare dintre rezultate - un fișier cu un octet sub o limită este accept, iar - regula la care se referă rămâne size_limit. -

    -
    - -
    -

    Ce conține manifestul?

    -

    - Se scrie lângă fișiere la sfârșitul fiecărei rulări, inclusiv a uneia întrerupte. O intrare pentru - fiecare fișier: -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "0.6.0-rc1" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - Se adaugă un recipe_hash când rularea a venit dintr-o rețetă și preset cu - overrides când a venit dintr-o presetare, astfel încât un manifest poate fi mereu - urmărit până la ce l-a produs. -

    -

    - Fiecare intrare poartă și target_id, id-ul targetului din rețeta care a produs - fișierul, iar summary.by_target numără fișierele la care a ajuns fiecare target. O - rețetă cu mai multe targeturi poate fi verificată astfel target cu target, fără a citi nume de - fișiere. -

    -
    - -
    -

    Ce este o presetare?

    -

    - Un set de fișiere gata făcut care răspunde unei întrebări de test obișnuite, ca să nu trebuiască să - proiectezi tu setul. Presetările sunt rețete obișnuite pe dedesubt, iar eject - afișează rețeta ca s-o poți edita de acolo. Fiecare presetare are o - pagină proprie cu ce găsește de obicei, ce este în set și fiecare setare pe care o acceptă. -

    +
    +

    Paginile documentației

    • -

      Gol și minimal

      -

      Trece un fișier valid, cât de mic permite formatul?

      -

      empty-and-minimal

      +

      Instalare EN

      +

      Descărcare pentru Windows, macOS sau Linux, verificarea arhivei sau instalare cu Docker, npm, pip ori Go.

    • -
    • -

      Gestionarea numelor de fișiere

      -

      Va stoca, va afișa și va returna sistemul meu un nume de fișier la care nu se aștepta?

      -

      filename-handling

      +
    • +

      Primii pași EN

      +

      Un prim fișier de dimensiune exactă, apoi zece mii, verificate, șterse și scrise ca rețetă.

    • -
    • -

      Dimensiuni de imagine

      -

      Acceptă sistemul meu imagini la dimensiunile folosite de ecrane și platforme?

      -

      picture-sizes

      +
    • +

      Comenzi EN

      +

      Fiecare comandă și fiecare opțiune cu valoarea implicită, și toate codurile de ieșire.

      +
    • +
    • +

      Scrierea rețetelor EN

      +

      Fiecare cheie a unei rețete, dimensiuni, nume de fișiere, reacții așteptate, deteriorări, arhive și presetări.

    • -

      Limite de dimensiune

      -

      Este o limită de dimensiune aplicată exact acolo unde este declarată?

      -

      size-boundaries

      +

      Galeria de rețete EN

      +

      Rețete gata de descărcat pentru încărcări, importuri, arhive, e-mail, media, CI și fișiere în masă.

      +
    • +
    • +

      Manifest EN

      +

      Fiecare câmp din manifest.json și cum îl citește un test.

    • -

      Import de tabele

      -

      Supraviețuiește importul meu de tabele la ce exportă instrumentele reale?

      -

      tabular-import

      +

      Setările formatelor EN

      +

      Fiecare setare a fiecărui format, cu valorile acceptate și valoarea implicită.

    • -

      Codarea textului

      -

      Știe cititorul meu în ce codare este un fișier sau doar ghicește?

      -

      text-encoding

      +

      Framework-uri de test EN

      +

      Fișierele în pytest, Playwright, Vitest și node:test.

      +
    • +
    • +

      Aplicația desktop EN

      +

      Fereastra, ecran cu ecran.

    • -

      Validarea încărcării

      -

      Acceptă formularul meu de încărcare ce trebuie și respinge restul?

      -

      upload-validation

      +

      Instrumente

      +

      Instrumente offline pentru fișierele tale: vezi dacă o arhivă poate fi dezarhivată în siguranță (zip slip, zip bomb) și verifică sau scrie sume SHA-256.

    -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show îți spune cât ar costa setul înainte să-l construiești și spune pe față când un - număr este o valoare provizorie de-a noastră, nu o limită de-a ta. -

    -
    -

    Ce înseamnă codurile de ieșire?

    -

    - Fiecare final are propriul cod, ieșirea citibilă de mașină merge la ieșirea standard, iar o rulare - eșuată nu tipărește nimic acolo. Tabelul este un contract înghețat - schimbarea sensului unui - cod cere o versiune majoră. -

    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    CodSemnificație
    0Totul a mers.
    1O eroare neașteptată în interiorul instrumentului.
    2Comandă sau opțiune greșită.
    3Rețeta nu este validă.
    4Formatul nu poate face ce s-a cerut.
    5O citire sau o scriere a eșuat.
    6Nu este destul spațiu pe disc.
    7verify a găsit o nepotrivire.
    8Rularea s-a terminat, dar nu s-a produs totul.
    130Întreruptă cu Ctrl+C.
    143Oprită de un semnal, așa arată o depășire de timp în CI.
    -
    -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - O rulare oprită cu Ctrl+C lasă totuși un manifest și nu lasă niciodată un fișier scris pe jumătate, - așa că un job anulat poate fi curățat de următorul. -

    -

    - Workflow-uri gata făcute pentru GitHub Actions și GitLab CI: - cum generezi fișiere de test într-un pipeline CI. -

    +
    +

    Ce face instrumentul, pe subiecte

    +
      +
    • +

      Formate

      +

      Toate formatele generate, cel mai mic fișier posibil pentru fiecare și setările acceptate. Toate cele 32 se deschid în programul căruia îi aparțin.

      +
    • +
    • +

      Presetări

      +

      Seturi gata făcute de fișiere de test, fiecare răspunde unei întrebări: limite de încărcare, nume de fișiere, codări, import de tabele, fișiere goale și validare.

      +
    • +
    • +

      Fișiere corupte

      +

      Un fișier stricat intenționat, de mărime exactă, cu un manifest care spune că sistemul tău trebuie să îl respingă. Pentru validarea încărcărilor și parsere.

      +
    • +
    • +

      Fișiere de exemplu

      +

      Fișiere de test de descărcat: câte unul de 1 MB din fiecare format, PDF, Word și Excel corupte, tabele CSV și imagini substituent, fiecare cu suma SHA-256.

      +
    • +
    • +

      Cazuri de test pentru încărcare

      +

      Cazuri de test pentru încărcarea fișierelor: limita de dimensiune, fișiere goale și corupte, tip greșit, nume neașteptate și arhive, fiecare cu fișierul lui.

      +
    • +
    • +

      Fișiere de test în CI

      +

      Generează fișiere de test în pipeline în loc să comiți binare: workflow GitHub Actions, job GitLab, coduri de ieșire și capcana PowerShell.

      +
    • +
    • +

      Dimensiune exactă

      +

      fsutil, dd, truncate și mkfile, fiecare măsurat pe sistemul lui, și de ce un fișier făcut așa nu e un PDF sau un PNG când un test are nevoie de unul.

      +
    • +
    -
    -

    Există o fereastră desktop?

    -

    - Da, același motor cu o fereastră deasupra, pentru testarea care nu e automatizată. Nu e o versiune - redusă: un test compară cele două interfețe capacitate cu capacitate, iar tot ce poate face doar - una dintre ele trebuie declarat și justificat, nu lăsat să divergă pe tăcute. -

    +
    +

    Tot nu merge?

    - Ecranele sunt un lot, presetări, mai multe loturi deodată și Despre. Arată cât ar costa o rulare - înainte să scrie ceva, raportează progresul cât rulează și poate fi anulată pe la jumătate fără - să lase un fișier scris pe jumătate. Nu deschide încă un fișier de rețetă - rețetele sunt - deocamdată treaba liniei de comandă, iar fereastra își construiește loturile în formular. + tfg <command> --help arată în terminal ce primește o comandă. Fiecare refuz numește setarea la care se referă, motivul și o valoare care ar funcționa. Dacă ceva nu se comportă cum spune o pagină de aici, semnalați-o. Este o greșeală a paginii sau a programului.

    diff --git a/web/public/ro/instrumente/index.html b/web/public/ro/instrumente/index.html index 43f7b50d..2adf1502 100644 --- a/web/public/ro/instrumente/index.html +++ b/web/public/ro/instrumente/index.html @@ -151,6 +151,21 @@
    +

    Documentație

    Verifică o arhivă înainte de dezarhivare și sumele de control

    diff --git a/web/public/ru/docs/index.html b/web/public/ru/docs/index.html index f3e95763..4dc02085 100644 --- a/web/public/ru/docs/index.html +++ b/web/public/ru/docs/index.html @@ -147,388 +147,93 @@

    Документация

    - Всё, что делает инструмент, разложено по вопросам, с которыми люди действительно приходят. - README в репозитории - полный справочник, и он всегда - соответствует скачанной вами сборке. + Как установить tfg, создать первые тестовые файлы, и всё, что программа принимает и записывает: каждая команда и каждый флаг, каждый ключ рецепта, каждое поле манифеста и каждая настройка каждого формата. Эти страницы на английском, потому что они создаются из самой программы при каждой сборке сайта и поэтому всегда говорят то, что делает версия, которую вы скачиваете.

    -
    -

    Какие есть команды?

    -

    Каждая делает одно дело:

    -
    tfg generate    создать файлы по рецепту или по флагам
    -tfg validate    проверить рецепт, ничего не записывая
    -tfg verify      сверить каталог с манифестом
    -tfg cleanup     удалить файлы, перечисленные в манифесте
    -tfg recipe fmt  вывести рецепт в устоявшемся виде
    -tfg preset      собрать набор файлов по именованному тестовому вопросу
    -tfg formats     перечислить форматы этой сборки
    -tfg damage      перечислить способы, которыми эта сборка может намеренно испортить файл
    -tfg tool        небольшие инструменты для уже имеющихся файлов
    -tfg version     вывести версию инструмента
    -tfg license     вывести лицензию и что она означает для созданных файлов
    -

    - В tfg tool собраны инструменты для уже имеющихся файлов, например проверка архива - перед распаковкой. На странице Инструменты описан каждый из них. -

    -
    - -
    -

    Как создать один файл точного размера?

    -

    - Укажите формат, размер и место назначения. Размеры считаются по 1024, поэтому 2mb - это - 2097152 байта. Подойдёт и простое число байт, так что --size 10485761 запрашивает - ровно столько. -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    Полезные флаги команды generate:

    -
    - - - - - - - - - - - - - - - - - -
    ФлагЧто делает
    --format <id>формат файлов, например txt
    --size <size>точный размер каждого файла, например 10mb или простое число байт
    --size-range <a-b>размер, выбираемый для каждого файла из диапазона, например 1kb-8kb. Выбор идёт от seed
    --boundary <size>три файла вокруг лимита: на байт меньше, сам лимит, на байт больше
    --count <n>сколько файлов создать. По умолчанию 1
    --name <template>шаблон имени, например invoice_{index:04}.txt
    --out <dir>каталог, в который записывать
    --seed <n>seed запуска. Один и тот же seed даёт те же байты
    --set <k>=<v>настройка формата, можно повторять
    --damage <name>намеренно испортить файлы, можно повторять, применяется по порядку. Список выводит tfg damage
    --expected <outcome>accept, reject, sanitize или unspecified
    --dry-runпосчитать и показать, ничего не записывая
    --jsonзаписать манифест в стандартный вывод
    -
    -
    - -
    -

    Как сделать намеренно сломанный файл?

    -

    - Любой другой файл, который записывает этот инструмент, корректен по построению, и это отвечает на - два из трёх вопросов, которые задаёт проверка загрузки. --damage отвечает на третий - - открывается ли файл вообще. Файл создаётся как обычно, а затем портится, поэтому у него - остаётся запрошенный размер. -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - Настройки указываются после двоеточия. Флаг можно повторять, и порядок записи - это порядок - применения. tfg damage перечисляет, что умеет эта сборка и что принимает каждый вид - повреждения. -

    -

    В рецепте ключ - это список имён или настроек:

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - Повреждённый файл получает в манифесте expected: reject с записанным рядом - повреждением. Две вещи отклоняются до записи чего-либо, потому что каждая оставила бы на диске - файл, неверно описанный манифестом: -

    -
      -
    • файл меньше, чем нужно повреждению, потому что он вышел бы без изменений
    • -
    • - expected: accept рядом с повреждением, потому что этому не мог бы соответствовать ни - один файл. Пишите sanitize, если тестируемая система должна починить файл, или - unspecified, если именно этот вопрос вы и задаёте -
    • -
    -

    - Третье заранее узнать нельзя. Если повреждение выполняется и не меняет ни одного байта, такой файл - отбрасывается, а не записывается - запуск продолжается, сообщает, что это был за файл, и - завершается кодом частичного завершения. -

    -

    - Шаг за шагом, с тестом, который читает манифест: как сделать - повреждённый файл для тестов. -

    -
    - -
    -

    Как выглядит рецепт?

    -

    - Рецепт - это файл YAML, описывающий целый запуск. Закоммитьте его рядом с тестами, и фикстуры - перестанут быть бинарными файлами в вашем репозитории - любой сможет пересоздать их байт в байт - из файла в несколько сотен символов. -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - Каждой цели нужен ровно один из ключей size, size-range, - boundary или contains. Два - это ошибка, и ни одного - тоже. - Недопустимый рецепт записывает ни одного файла и сообщает обо всех проблемах - сразу, а не только о первой, называя каждый раз настройку, к которой она относится. -

    -
    - -
    -

    Как объявить, что моя система должна делать с файлом?

    -

    Краткая форма, когда достаточно исхода, и длинная, когда важна причина:

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - Исходы - accept, reject, sanitize и unspecified. - Причины образуют закрытый список, чтобы отчёт мог по ним группировать: - content_malformed, count_limit, dimensions_limit, - duplicate, encoding_invalid, extension_rule, - filename_invalid, filename_too_long, filename_traversal, - malware_signature, mime_mismatch, nesting_depth, - none, size_limit и size_zero. -

    -

    - Причина называет действующее правило, а не вердикт. Поэтому одна и та же причина - может стоять под любым исходом - файл на байт меньше лимита получает accept, а - правило, о котором речь, всё равно size_limit. -

    -
    - -
    -

    Что в манифесте?

    -

    - Он записывается рядом с файлами в конце каждого запуска, в том числе прерванного. Одна запись на - файл: -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "0.6.0-rc1" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - recipe_hash добавляется, если запуск был по рецепту, а preset с - overrides - если по пресету, так что манифест всегда можно отследить до того, что - его создало. -

    -

    - Каждая запись также содержит target_id - id цели рецепта, которая создала файл, а - summary.by_target считает файлы каждой цели. Рецепт с несколькими целями можно - поэтому проверить цель за целью, не читая имена файлов. -

    -
    - -
    -

    Что такое пресет?

    -

    - Готовый набор файлов, отвечающий на распространённый тестовый вопрос, чтобы вам не приходилось - проектировать набор самостоятельно. Пресеты - обычные рецепты внутри, а eject - выводит рецепт, чтобы вы могли отредактировать его. У каждого пресета есть - отдельная страница о том, что он обычно находит, что входит в набор и - какие настройки принимает. -

    +
    +

    Страницы документации

    • -

      Пустые и минимальные

      -

      Пройдёт ли корректный файл, настолько маленький, насколько позволяет формат?

      -

      empty-and-minimal

      +

      Установка EN

      +

      Скачать для Windows, macOS или Linux, проверить архив или установить через Docker, npm, pip или Go.

    • -
    • -

      Обработка имён файлов

      -

      Сохранит, покажет и вернёт ли моя система имя файла, которого не ожидала?

      -

      filename-handling

      +
    • +

      Первые шаги EN

      +

      Первый файл точного размера, затем десять тысяч, проверенные, удалённые и записанные как рецепт.

    • -
    • -

      Размеры изображений

      -

      Принимает ли моя система изображения тех размеров, которые используют экраны и платформы?

      -

      picture-sizes

      +
    • +

      Команды EN

      +

      Каждая команда и каждый флаг со значением по умолчанию, и все коды завершения.

      +
    • +
    • +

      Как писать рецепты EN

      +

      Каждый ключ рецепта, размеры, имена файлов, ожидаемые реакции, повреждения, архивы и пресеты.

    • -

      Границы размера

      -

      Применяется ли лимит размера ровно там, где он объявлен?

      -

      size-boundaries

      +

      Галерея рецептов EN

      +

      Готовые рецепты для загрузки: выгрузки, импорт, архивы, почта, медиа, CI и массовые файлы.

      +
    • +
    • +

      Манифест EN

      +

      Каждое поле manifest.json и то, как его читает тест.

    • -

      Импорт таблиц

      -

      Переживёт ли мой импорт таблиц то, что экспортируют настоящие инструменты?

      -

      tabular-import

      +

      Настройки форматов EN

      +

      Каждая настройка каждого формата с допустимыми значениями и значением по умолчанию.

    • -

      Кодировка текста

      -

      Знает ли мой читатель, в какой кодировке файл, или угадывает?

      -

      text-encoding

      +

      Тестовые фреймворки EN

      +

      Файлы внутри pytest, Playwright, Vitest и node:test.

      +
    • +
    • +

      Настольное приложение EN

      +

      Окно программы, экран за экраном.

    • -

      Проверка загрузки

      -

      Принимает ли моя форма загрузки то, что должна, и отклоняет ли остальное?

      -

      upload-validation

      +

      Инструменты

      +

      Офлайн-инструменты для уже имеющихся файлов: безопасно ли распаковывать архив, включая zip slip и zip-бомбы, а также проверка и запись сумм SHA-256.

    -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show сообщает, чего стоил бы набор, прежде чем вы его соберёте, и прямо говорит, когда - число - наша временная подстановка, а не ваш лимит. -

    -
    -

    Что означают коды завершения?

    -

    - У каждого исхода свой код, машиночитаемый вывод идёт в стандартный вывод, а неудачный запуск ничего - туда не печатает. Таблица - замороженный контракт: смена значения кода требует повышения - мажорной версии. -

    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    КодЗначение
    0Всё сработало.
    1Непредвиденная ошибка внутри инструмента.
    2Неверная команда или флаг.
    3Рецепт недопустим.
    4Формат не может сделать то, что запрошено.
    5Не удалось прочитать или записать.
    6Недостаточно места на диске.
    7verify обнаружил расхождение.
    8Запуск завершён, но создано не всё.
    130Прерван с помощью Ctrl+C.
    143Остановлен сигналом, так выглядит тайм-аут в CI.
    -
    -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - Запуск, остановленный с помощью Ctrl+C, всё равно оставляет манифест и никогда не оставляет - наполовину записанный файл, поэтому отменённое задание может быть убрано следующим. -

    -

    - Готовые workflow для GitHub Actions и GitLab CI: как генерировать - тестовые файлы в конвейере CI. -

    +
    +

    Что делает инструмент, по темам

    +
      +
    • +

      Форматы

      +

      Все форматы, которые создаёт генератор, самый маленький возможный файл каждого и допустимые настройки. Все 32 открываются в своих программах.

      +
    • +
    • +

      Пресеты

      +

      Готовые наборы тестовых файлов, каждый отвечает на один вопрос: лимиты загрузки, имена файлов, кодировки, импорт таблиц, пустые файлы и проверка загрузки.

      +
    • +
    • +

      Повреждённые файлы

      +

      Намеренно испорченный файл точного размера с манифестом, который говорит, что ваша система должна его отклонить. Для проверки валидации загрузки и парсеров.

      +
    • +
    • +

      Примеры файлов

      +

      Тестовые файлы для скачивания: по одному каждого формата по 1 МБ, повреждённые PDF, Word и Excel, таблицы CSV и изображения-заглушки, каждый с суммой SHA-256.

      +
    • +
    • +

      Тест-кейсы загрузки

      +

      Тест-кейсы для загрузки файлов: лимит размера, пустые и повреждённые файлы, неверный тип, неожиданные имена и архивы, у каждого свой файл для проверки.

      +
    • +
    • +

      Тестовые файлы в CI

      +

      Генерируйте тестовые файлы в конвейере, а не коммитьте бинарники: workflow GitHub Actions, задание GitLab, коды завершения и ловушка PowerShell.

      +
    • +
    • +

      Точный размер

      +

      fsutil, dd, truncate и mkfile, каждая команда измерена в своей системе, и почему такой файл не является PDF или PNG, когда тесту нужен настоящий.

      +
    • +
    -
    -

    Есть ли десктопное окно?

    -

    - Да, тот же движок с окном сверху, для тестирования, которое не автоматизируется. Это не урезанная - версия: тест сравнивает два интерфейса возможность за возможностью, и всё, что умеет только один - из них, должно быть объявлено и обосновано, а не тихо расходиться. -

    +
    +

    Всё ещё не получается?

    - Экраны: одна партия, пресеты, несколько партий одновременно и о программе. Окно показывает, чего - стоил бы запуск, прежде чем что-либо записать, отображает ход работы и может быть отменено на - полпути без наполовину записанного файла. Файл рецепта оно пока не открывает - рецепты пока дело - командной строки, а окно собирает свои партии в форме. + tfg <command> --help показывает в терминале, что принимает команда. Каждый отказ называет настройку, о которой идёт речь, причину и значение, которое подойдёт. Если что-то работает не так, как сказано на странице, сообщите об этом. Это ошибка страницы или программы.

    diff --git a/web/public/ru/tools/index.html b/web/public/ru/tools/index.html index 5960b509..a492d066 100644 --- a/web/public/ru/tools/index.html +++ b/web/public/ru/tools/index.html @@ -151,6 +151,21 @@
    +

    Документация

    Проверка архива перед распаковкой и сверка контрольных сумм

    diff --git a/web/public/sitemap.xml b/web/public/sitemap.xml index 8b14dc0e..5cd3aac4 100644 --- a/web/public/sitemap.xml +++ b/web/public/sitemap.xml @@ -33,6 +33,33 @@ https://testingfilesgenerator.donislawdev.com/file-upload-test-cases/ + + https://testingfilesgenerator.donislawdev.com/docs/install/ + + + https://testingfilesgenerator.donislawdev.com/docs/getting-started/ + + + https://testingfilesgenerator.donislawdev.com/docs/commands/ + + + https://testingfilesgenerator.donislawdev.com/docs/recipes/ + + + https://testingfilesgenerator.donislawdev.com/recipes/ + + + https://testingfilesgenerator.donislawdev.com/docs/manifest/ + + + https://testingfilesgenerator.donislawdev.com/docs/format-settings/ + + + https://testingfilesgenerator.donislawdev.com/docs/test-frameworks/ + + + https://testingfilesgenerator.donislawdev.com/docs/desktop-app/ + https://testingfilesgenerator.donislawdev.com/tools/ diff --git a/web/public/test-files-in-ci/index.html b/web/public/test-files-in-ci/index.html index 0d637d45..1202b157 100644 --- a/web/public/test-files-in-ci/index.html +++ b/web/public/test-files-in-ci/index.html @@ -285,7 +285,7 @@

    What makes a step fail, and why

    A failed run prints nothing on standard output, so a log parser never reads an error as data. The - whole table is on the documentation page. + whole table is on the page of commands.

    diff --git a/web/public/th/docs/index.html b/web/public/th/docs/index.html index 0f77441d..9ad4f4ac 100644 --- a/web/public/th/docs/index.html +++ b/web/public/th/docs/index.html @@ -147,379 +147,93 @@

    เอกสาร

    - ทุกอย่างที่เครื่องมือทำได้ จัดเรียงตามคำถามที่ผู้คนมาถามจริงๆ README - ในรีโพซิทอรีเป็นข้อมูลอ้างอิงฉบับสมบูรณ์และตรงกับบิลด์ที่คุณดาวน์โหลดเสมอ + วิธีติดตั้ง tfg สร้างไฟล์ทดสอบชุดแรก และทุกอย่างที่โปรแกรมรับและเขียน ได้แก่ ทุกคำสั่งและทุกแฟล็ก ทุกคีย์ของสูตร ทุกฟิลด์ของแมนิเฟสต์ และทุกการตั้งค่าของทุกรูปแบบไฟล์ หน้าเหล่านี้เป็นภาษาอังกฤษ เพราะสร้างจากตัวโปรแกรมเองทุกครั้งที่สร้างเว็บไซต์ จึงตรงกับสิ่งที่เวอร์ชันที่คุณดาวน์โหลดทำเสมอ

    -
    -

    มีคำสั่งอะไรบ้าง

    -

    แต่ละคำสั่งทำสิ่งเดียว:

    -
    tfg generate    สร้างไฟล์จากสูตรหรือจากแฟลก
    -tfg validate    ตรวจสอบสูตรโดยไม่เขียนอะไร
    -tfg verify      ตรวจสอบไดเรกทอรีเทียบกับแมนิเฟสต์
    -tfg cleanup     ลบไฟล์ที่แมนิเฟสต์ระบุไว้
    -tfg recipe fmt  พิมพ์สูตรในรูปแบบมาตรฐาน
    -tfg preset      สร้างชุดไฟล์จากคำถามทดสอบที่มีชื่อ
    -tfg formats     แสดงรายการรูปแบบที่บิลด์นี้รองรับ
    -tfg damage      แสดงรายการวิธีที่บิลด์นี้ทำให้ไฟล์เสียหายโดยตั้งใจ
    -tfg tool        เครื่องมือเล็กๆ สำหรับไฟล์ที่คุณมีอยู่แล้ว
    -tfg version     พิมพ์เวอร์ชันของเครื่องมือ
    -tfg license     พิมพ์ใบอนุญาตและความหมายสำหรับไฟล์ที่สร้างขึ้น
    -

    - tfg tool รวมเครื่องมือสำหรับไฟล์ที่คุณมีอยู่แล้ว เช่น การตรวจไฟล์บีบอัดก่อนแตกไฟล์ - เครื่องมือ อธิบายเครื่องมือแต่ละตัว -

    -
    - -
    -

    สร้างไฟล์เดียวที่ขนาดแม่นยำได้อย่างไร

    -

    - ระบุรูปแบบ ขนาด และปลายทาง ขนาดนับเป็นทีละ 1024 ดังนั้น 2mb คือ 2097152 ไบต์ - ใช้จำนวนไบต์ธรรมดาก็ได้ ดังนั้น --size 10485761 ขอจำนวนนั้นพอดี -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    แฟลกที่มีประโยชน์ของ generate:

    -
    - - - - - - - - - - - - - - - - - -
    แฟลกทำอะไร
    --format <id>รูปแบบของไฟล์ เช่น txt
    --size <size>ขนาดที่แม่นยำของแต่ละไฟล์ เช่น 10mb หรือจำนวนไบต์ธรรมดา
    --size-range <a-b>ขนาดที่สุ่มต่อไฟล์จากช่วง เช่น 1kb-8kb การสุ่มมาจากซีด
    --boundary <size>สามไฟล์รอบขีดจำกัด: น้อยกว่าหนึ่งไบต์ เท่ากับขีดจำกัด และมากกว่าหนึ่งไบต์
    --count <n>จะสร้างกี่ไฟล์ ค่าเริ่มต้น 1
    --name <template>แม่แบบชื่อ เช่น invoice_{index:04}.txt
    --out <dir>ไดเรกทอรีที่จะเขียนลงไป
    --seed <n>ซีดของการรัน ซีดเดียวกันให้ไบต์เดียวกัน
    --set <k>=<v>การตั้งค่ารูปแบบ ระบุซ้ำได้
    --damage <name>ทำให้ไฟล์เสียหายโดยตั้งใจ ระบุซ้ำได้และใช้ตามลำดับ รัน tfg damage เพื่อดูรายการ
    --expected <outcome>accept, reject, sanitize หรือ unspecified
    --dry-runนับและแสดง ไม่เขียนอะไรเลย
    --jsonเขียนแมนิเฟสต์ไปยังเอาต์พุตมาตรฐาน
    -
    -
    - -
    -

    ทำไฟล์ที่เสียโดยตั้งใจได้อย่างไร

    -

    - ไฟล์อื่นทุกไฟล์ที่เครื่องมือนี้เขียนถูกต้องโดยโครงสร้าง - ซึ่งตอบสองในสามคำถามที่ตัวตรวจสอบการอัปโหลดถาม --damage ตอบข้อที่สาม - - ไฟล์เปิดได้หรือไม่ ไฟล์ถูกสร้างตามปกติแล้วจึงถูกทำให้เสีย จึงยังคงมีขนาดที่คุณขอ -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - การตั้งค่าอยู่หลังเครื่องหมายทวิภาค แฟลกระบุซ้ำได้ และลำดับที่คุณเขียนคือลำดับที่ใช้ tfg - damage แสดงว่าบิลด์นี้ทำอะไรได้บ้างและแต่ละแบบรับอะไร -

    -

    ในสูตร คีย์เป็นรายการ ของชื่อหรือของการตั้งค่า:

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - ไฟล์ที่เสียหายได้ expected: reject ในแมนิเฟสต์ พร้อมบันทึกความเสียหายไว้ข้างๆ - สองอย่างถูกปฏิเสธก่อนจะเขียนอะไร เพราะแต่ละอย่างจะวางไฟล์ที่แมนิเฟสต์อธิบายผิดไว้บนดิสก์: -

    -
      -
    • ไฟล์ที่เล็กกว่าที่ความเสียหายต้องการ เพราะจะออกมาโดยไม่เปลี่ยนแปลง
    • -
    • - expected: accept ข้างความเสียหาย เพราะไม่มีสิ่งใดทำให้เป็นจริงได้ เขียน - sanitize ถ้าระบบที่ทดสอบควรซ่อมไฟล์ หรือ unspecified - ถ้านั่นคือคำถามที่คุณกำลังถาม -
    • -
    -

    - ข้อที่สามรู้ล่วงหน้าไม่ได้ ถ้าความเสียหายทำงานแล้วไม่ขยับไบต์ใดเลย ไฟล์นั้นจะถูกทิ้งแทนที่จะถูกเขียน - - การรันดำเนินต่อ บอกว่าเป็นไฟล์ไหน และจบด้วยรหัสออกแบบบางส่วน -

    -

    - ทีละขั้น พร้อมการทดสอบที่อ่านแมนิเฟสต์: - วิธีทำไฟล์เสียหายสำหรับการทดสอบ -

    -
    - -
    -

    สูตรหน้าตาเป็นอย่างไร

    -

    - สูตรคือไฟล์ YAML ที่อธิบายการรันทั้งหมด คอมมิตไว้ข้างการทดสอบของคุณ - แล้วฟิกซ์เจอร์จะไม่เป็นไบนารีในรีโพซิทอรีอีกต่อไป - ใครก็สร้างใหม่ได้ ไบต์ต่อไบต์ - จากไฟล์ที่ยาวไม่กี่ร้อยอักขระ -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - แต่ละ target ต้องมี size, size-range, boundary หรือ - contains อย่างใดอย่างหนึ่งพอดี มีสองอย่างคือข้อผิดพลาด ไม่มีเลยก็เป็นข้อผิดพลาด - สูตรที่ไม่ถูกต้องไม่เขียนไฟล์ใดเลย - และรายงานปัญหาทั้งหมดพร้อมกันแทนที่จะรายงานแค่ข้อแรก โดยแต่ละข้อระบุการตั้งค่าที่เกี่ยวข้อง -

    -
    - -
    -

    ประกาศอย่างไรว่าระบบของฉันควรทำอะไรกับไฟล์

    -

    ใช้รูปแบบสั้นเมื่อผลลัพธ์เพียงพอ ใช้รูปแบบยาวเมื่อเหตุผลสำคัญ:

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - ผลลัพธ์คือ accept, reject, sanitize และ - unspecified เหตุผลเป็นรายการปิดเพื่อให้รายงานจัดกลุ่มตามได้: - content_malformed, count_limit, dimensions_limit, - duplicate, encoding_invalid, extension_rule, - filename_invalid, filename_too_long, filename_traversal, - malware_signature, mime_mismatch, nesting_depth, - none, size_limit และ size_zero -

    -

    - เหตุผลระบุกฎที่เกี่ยวข้อง ไม่ใช่คำตัดสิน - ด้วยเหตุนี้เหตุผลเดียวกันจึงอยู่ใต้ผลลัพธ์ใดก็ได้ - ไฟล์ที่น้อยกว่าขีดจำกัดหนึ่งไบต์คือ - accept และกฎที่เกี่ยวข้องก็ยังเป็น size_limit -

    -
    - -
    -

    แมนิเฟสต์มีอะไรบ้าง

    -

    - ถูกเขียนไว้ข้างไฟล์เมื่อจบทุกการรัน รวมถึงการรันที่ถูกขัดจังหวะ หนึ่งรายการต่อไฟล์: -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "0.6.0-rc1" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - recipe_hash จะถูกเพิ่มเมื่อการรันมาจากสูตร และ preset พร้อม - overrides เมื่อมาจากพรีเซ็ต แมนิเฟสต์จึงสืบย้อนไปถึงสิ่งที่สร้างมันได้เสมอ -

    -

    - ทุกรายการยังมี target_id ซึ่งเป็นรหัสของ target ในสูตรที่สร้างไฟล์ และ - summary.by_target นับจำนวนไฟล์ที่แต่ละ target สร้างได้ สูตรที่มีหลาย target - จึงตรวจทีละ target ได้โดยไม่ต้องอ่านชื่อไฟล์ -

    -
    - -
    -

    พรีเซ็ตคืออะไร

    -

    - ชุดไฟล์สำเร็จรูปที่ตอบคำถามการทดสอบที่พบบ่อย คุณจึงไม่ต้องออกแบบชุดเอง - พรีเซ็ตเป็นสูตรธรรมดาอยู่ข้างใน และ eject - พิมพ์สูตรออกมาเพื่อให้คุณแก้ไขต่อจากตรงนั้น - แต่ละพรีเซ็ตมีหน้าของตัวเองที่บอกว่าโดยทั่วไปมันพบอะไร ในชุดมีอะไร - และรับการตั้งค่าใดบ้าง -

    +
    +

    หน้าเอกสาร

    • -

      ไฟล์ว่างและขั้นต่ำ

      -

      ไฟล์ที่ถูกต้องและเล็กเท่าที่รูปแบบอนุญาตจะผ่านไหม

      -

      empty-and-minimal

      +

      การติดตั้ง EN

      +

      ดาวน์โหลดสำหรับ Windows, macOS หรือ Linux ตรวจสอบไฟล์บีบอัด หรือติดตั้งด้วย Docker, npm, pip หรือ Go

    • -
    • -

      การจัดการชื่อไฟล์

      -

      ระบบของฉันจะเก็บ แสดง และส่งคืนชื่อไฟล์ที่ไม่ได้คาดไว้ได้ไหม

      -

      filename-handling

      +
    • +

      เริ่มต้นใช้งาน EN

      +

      ไฟล์แรกขนาดพอดี แล้วหนึ่งหมื่นไฟล์ ตรวจสอบ ลบ และเขียนเป็นสูตร

    • -
    • -

      ขนาดรูปภาพ

      -

      ระบบของฉันรับรูปภาพในขนาดที่หน้าจอและแพลตฟอร์มใช้หรือไม่

      -

      picture-sizes

      +
    • +

      คำสั่ง EN

      +

      ทุกคำสั่งและทุกแฟล็กพร้อมค่าเริ่มต้น และรหัสออกทั้งหมด

      +
    • +
    • +

      การเขียนสูตร EN

      +

      ทุกคีย์ของสูตร ขนาด ชื่อไฟล์ ปฏิกิริยาที่คาดหวัง ความเสียหาย ไฟล์บีบอัด และพรีเซ็ต

    • -

      ขอบเขตขนาด

      -

      ขีดจำกัดขนาดถูกบังคับใช้ตรงจุดที่ประกาศไว้พอดีหรือไม่

      -

      size-boundaries

      +

      คลังสูตร EN

      +

      สูตรพร้อมดาวน์โหลดสำหรับการอัปโหลด การนำเข้า ไฟล์บีบอัด อีเมล สื่อ CI และไฟล์จำนวนมาก

      +
    • +
    • +

      แมนิเฟสต์ EN

      +

      ทุกฟิลด์ของ manifest.json และวิธีที่การทดสอบอ่าน

    • -

      การนำเข้าตาราง

      -

      การนำเข้าตารางของฉันรับมือกับสิ่งที่เครื่องมือจริงส่งออกได้ไหม

      -

      tabular-import

      +

      การตั้งค่ารูปแบบไฟล์ EN

      +

      ทุกการตั้งค่าของทุกรูปแบบไฟล์ พร้อมค่าที่รับได้และค่าเริ่มต้น

    • -

      การเข้ารหัสข้อความ

      -

      ตัวอ่านของฉันรู้ไหมว่าไฟล์ใช้การเข้ารหัสอะไร หรือกำลังเดาอยู่

      -

      text-encoding

      +

      เฟรมเวิร์กการทดสอบ EN

      +

      ไฟล์ภายใน pytest, Playwright, Vitest และ node:test

      +
    • +
    • +

      แอปเดสก์ท็อป EN

      +

      หน้าต่างโปรแกรม ทีละหน้าจอ

    • -

      การตรวจสอบการอัปโหลด

      -

      ฟอร์มอัปโหลดของฉันรับสิ่งที่ควรรับและปฏิเสธที่เหลือหรือไม่

      -

      upload-validation

      +

      เครื่องมือ

      +

      เครื่องมือออฟไลน์สำหรับไฟล์ที่คุณมีอยู่แล้ว: ดูว่าไฟล์บีบอัดแตกได้อย่างปลอดภัยไหม รวมถึง zip slip และ zip bomb และตรวจหรือเขียนเช็กซัม SHA-256

    -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show บอกว่าชุดจะมีต้นทุนเท่าไรก่อนที่คุณจะสร้าง และบอกตรงๆ - เมื่อตัวเลขใดเป็นค่าชั่วคราวของเรา ไม่ใช่ขีดจำกัดของคุณ -

    -
    -

    รหัสออกมีความหมายอย่างไร

    -

    - ทุกการจบมีรหัสของตัวเอง เอาต์พุตที่เครื่องอ่านได้ไปที่เอาต์พุตมาตรฐาน - และการรันที่ล้มเหลวไม่พิมพ์อะไรที่นั่น ตารางนี้เป็นสัญญาที่ตรึงไว้ - - การเปลี่ยนความหมายของรหัสต้องเลื่อนเวอร์ชันหลัก -

    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    รหัสความหมาย
    0ทุกอย่างทำงานได้
    1เกิดข้อผิดพลาดที่ไม่คาดคิดภายในเครื่องมือ
    2คำสั่งหรือแฟลกไม่ถูกต้อง
    3สูตรไม่ถูกต้อง
    4รูปแบบนี้ทำสิ่งที่ขอไม่ได้
    5การอ่านหรือเขียนล้มเหลว
    6พื้นที่ดิสก์ไม่พอ
    7verify พบความไม่ตรงกัน
    8การรันเสร็จสิ้น แต่สร้างไม่ครบทุกอย่าง
    130ถูกขัดจังหวะด้วย Ctrl+C
    143ถูกหยุดด้วยสัญญาณ ซึ่งเป็นหน้าตาของการหมดเวลาใน CI
    -
    -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - การรันที่หยุดด้วย Ctrl+C ยังทิ้งแมนิเฟสต์ไว้ และไม่เคยทิ้งไฟล์ที่เขียนค้างครึ่งหนึ่ง - งานที่ถูกยกเลิกจึงยังถูกทำความสะอาดโดยงานถัดไปได้ -

    -

    - เวิร์กโฟลว์สำเร็จรูปสำหรับ GitHub Actions และ GitLab CI: - วิธีสร้างไฟล์ทดสอบในไปป์ไลน์ CI -

    +
    +

    เครื่องมือนี้ทำอะไรได้ แยกตามหัวข้อ

    +
      +
    • +

      รูปแบบไฟล์

      +

      รูปแบบไฟล์ทั้งหมดที่ตัวสร้างทำได้ ไฟล์เล็กที่สุดที่เป็นไปได้ของแต่ละรูปแบบ และการตั้งค่าที่รองรับ ทั้ง 32 รูปแบบเปิดได้ในซอฟต์แวร์ของมัน

      +
    • +
    • +

      พรีเซ็ต

      +

      ชุดไฟล์ทดสอบสำเร็จรูป แต่ละชุดตอบคำถามการทดสอบข้อเดียว ได้แก่ ขีดจำกัดการอัปโหลด ชื่อไฟล์ การเข้ารหัส การนำเข้าตาราง ไฟล์ว่าง และการตรวจสอบการอัปโหลด

      +
    • +
    • +

      ไฟล์เสียหาย

      +

      ไฟล์ที่ตั้งใจทำให้เสีย ขนาดตรงเป๊ะ พร้อมแมนิเฟสต์ที่บอกว่าระบบของคุณควรปฏิเสธ สำหรับทดสอบการตรวจสอบการอัปโหลดและตัวแยกวิเคราะห์

      +
    • +
    • +

      ไฟล์ตัวอย่าง

      +

      ดาวน์โหลดไฟล์ตัวอย่างสำหรับทดสอบ ทุกรูปแบบรูปแบบละหนึ่งไฟล์ขนาด 1 MB ไฟล์ PDF, Word และ Excel ที่เสียหาย ตาราง CSV และภาพตัวยึดตำแหน่ง ทุกไฟล์มีค่า SHA-256 กำกับ

      +
    • +
    • +

      กรณีทดสอบการอัปโหลด

      +

      กรณีทดสอบการอัปโหลดไฟล์: ขีดจำกัดขนาด ไฟล์ว่างและไฟล์เสียหาย ชนิดไฟล์ผิด ชื่อไฟล์ที่ไม่คาดคิด และไฟล์บีบอัด แต่ละกรณีมาพร้อมไฟล์ที่ใช้ทดสอบ

      +
    • +
    • +

      ไฟล์ทดสอบใน CI

      +

      สร้างไฟล์ทดสอบในไปป์ไลน์แทนการคอมมิตไบนารี: เวิร์กโฟลว์ GitHub Actions งาน GitLab รหัสออก และกับดักของ PowerShell

      +
    • +
    • +

      ขนาดแม่นยำ

      +

      fsutil, dd, truncate และ mkfile วัดผลบนระบบของแต่ละคำสั่ง และเหตุผลที่ไฟล์ที่สร้างวิธีนี้ใช้ไม่ได้เมื่อการทดสอบต้องการ PDF หรือ PNG

      +
    • +
    -
    -

    มีหน้าต่างเดสก์ท็อปไหม

    -

    - มี เป็นเอนจินเดียวกันที่มีหน้าต่างครอบอยู่ สำหรับการทดสอบที่ไม่ได้เขียนสคริปต์ ไม่ใช่ฉบับตัดทอน: - มีการทดสอบเปรียบเทียบสองอินเทอร์เฟซทีละความสามารถ - และสิ่งที่ทำได้เพียงฝั่งเดียวต้องถูกประกาศและให้เหตุผล แทนที่จะแยกจากกันไปอย่างเงียบๆ -

    +
    +

    ยังติดอยู่ใช่ไหม

    - หน้าจอมีชุดเดียว พรีเซ็ต หลายชุดพร้อมกัน และเกี่ยวกับ แสดงต้นทุนของการรันก่อนเขียนอะไร - รายงานความคืบหน้าขณะรัน และยกเลิกกลางคันได้โดยไม่ทิ้งไฟล์ที่เขียนค้างครึ่งหนึ่ง - ยังเปิดไฟล์สูตรไม่ได้ - ตอนนี้สูตรเป็นเรื่องของบรรทัดคำสั่ง และหน้าต่างสร้างชุดในฟอร์ม + tfg <command> --help จะแสดงในเทอร์มินัลว่าคำสั่งหนึ่งรับอะไรบ้าง ทุกครั้งที่ปฏิเสธจะบอกการตั้งค่าที่เกี่ยวข้อง เหตุผล และค่าที่ใช้ได้ หากบางอย่างไม่ทำงานตามที่หน้านี้บอก โปรดแจ้งเรา นั่นคือข้อผิดพลาดของหน้าหรือของโปรแกรม

    diff --git a/web/public/th/tools/index.html b/web/public/th/tools/index.html index 3cdc5c30..e58208c8 100644 --- a/web/public/th/tools/index.html +++ b/web/public/th/tools/index.html @@ -151,6 +151,21 @@
    +

    เอกสาร

    ตรวจไฟล์บีบอัดก่อนแตกไฟล์ และตรวจสอบเช็กซัม

    diff --git a/web/public/tools/index.html b/web/public/tools/index.html index ad819ea1..5d5ff3ea 100644 --- a/web/public/tools/index.html +++ b/web/public/tools/index.html @@ -151,6 +151,21 @@

    +

    Documentation

    Check an archive before unpacking it, and verify checksums

    diff --git a/web/public/tr/araclar/index.html b/web/public/tr/araclar/index.html index bff5a5ff..f8641ec3 100644 --- a/web/public/tr/araclar/index.html +++ b/web/public/tr/araclar/index.html @@ -151,6 +151,21 @@

    +

    Dokümantasyon

    Bir arşivi açmadan önce denetleme ve sağlama toplamlarını doğrulama

    diff --git a/web/public/tr/dokumantasyon/index.html b/web/public/tr/dokumantasyon/index.html index 65bff29c..6523ef5b 100644 --- a/web/public/tr/dokumantasyon/index.html +++ b/web/public/tr/dokumantasyon/index.html @@ -147,385 +147,93 @@

    Dokümantasyon

    - Aracın yaptığı her şey, insanların gerçekten geldiği sorular şeklinde düzenlendi. - Depodaki README tam başvurudur ve her zaman indirdiğiniz sürümle - eşleşir. + tfg nasıl kurulur, ilk test dosyalarınız nasıl yapılır ve programın aldığı ve yazdığı her şey: her komut ve her seçenek, bir tarifin her anahtarı, manifestin her alanı ve her biçimin her ayarı. Bu sayfalar İngilizcedir, çünkü site her oluşturulduğunda programın kendisinden üretilirler ve bu yüzden her zaman indirdiğiniz sürümün ne yaptığını söylerler.

    -
    -

    Hangi komutlar var?

    -

    Her biri tek bir iş yapar:

    -
    tfg generate    tariften veya bayraklardan dosya üret
    -tfg validate    bir tarifi denetle, hiçbir şey yazma
    -tfg verify      bir dizini bir manifeste göre denetle
    -tfg cleanup     bir manifestin listelediği dosyaları sil
    -tfg recipe fmt  bir tarifi oturmuş biçiminde yazdır
    -tfg preset      adlandırılmış bir test sorusundan dosya seti oluştur
    -tfg formats     bu sürümün desteklediği biçimleri listele
    -tfg damage      bu sürümün bir dosyayı kasıtlı bozma yollarını listele
    -tfg tool        elinizdeki dosyalar için küçük araçlar
    -tfg version     araç sürümünü yazdır
    -tfg license     lisansı ve üretilen dosyalar için anlamını yazdır
    -

    - tfg tool, elinizdeki dosyalar için araçları içerir, örneğin bir arşivi açmadan önce - denetlemek. Araçlar sayfası her birini anlatır. -

    -
    - -
    -

    Tam boyutta tek bir dosyayı nasıl üretirim?

    -

    - Biçimi, boyutu ve nereye gideceğini söyleyin. Boyutlar 1024'lerle sayılır, yani 2mb - 2097152 bayttır. Düz bir bayt sayısı da olur, yani --size 10485761 tam o kadarını - ister. -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    generate için işe yarar bayraklar:

    -
    - - - - - - - - - - - - - - - - - -
    BayrakNe yapar
    --format <id>dosyaların biçimi, örneğin txt
    --size <size>her dosyanın tam boyutu, 10mb gibi veya düz bir bayt sayısı
    --size-range <a-b>bir aralıktan dosya başına çekilen boyut, 1kb-8kb gibi. Çekiliş seed'den gelir
    --boundary <size>bir sınırın çevresinde üç dosya: bir bayt altı, sınırın kendisi, bir bayt üstü
    --count <n>kaç dosya üretileceği. Varsayılan 1
    --name <template>ad şablonu, örneğin invoice_{index:04}.txt
    --out <dir>yazılacak dizin
    --seed <n>çalıştırmanın seed'i. Aynı seed aynı baytları verir
    --set <k>=<v>bir biçim ayarı, tekrarlanabilir
    --damage <name>dosyaları kasıtlı bozar, tekrarlanabilir ve sırayla uygulanır. Liste için tfg damage çalıştırın
    --expected <outcome>accept, reject, sanitize veya unspecified
    --dry-runsay ve göster, hiçbir şey yazma
    --jsonmanifesti standart çıktıya yaz
    -
    -
    - -
    -

    Kasıtlı bozuk bir dosyayı nasıl yaparım?

    -

    - Bu aracın yazdığı diğer her dosya yapısı gereği doğrudur ve bu, bir yükleme doğrulayıcısının sorduğu - üç sorudan ikisini yanıtlar. --damage üçüncüsünü yanıtlar - dosya hiç açılıyor mu. - Dosya normal üretilir, sonra bozulur, böylece hâlâ istediğiniz boyuttadır. -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - Ayarlar iki noktadan sonra gelir. Bayrak tekrarlanır ve yazdığınız sıra uygulanma sırasıdır. - tfg damage bu sürümün neler yapabildiğini ve her birinin ne aldığını listeler. -

    -

    Bir tarifte anahtar, adlardan veya ayarlardan oluşan bir listedir:

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - Hasarlı bir dosya manifestte expected: reject alır, hasar yanında kaydedilir. İki şey - bir şey yazılmadan önce reddedilir, çünkü her biri aksi hâlde diske manifestin yanlış tarif - ettiği bir dosya koyardı: -

    -
      -
    • hasarın gerektirdiğinden küçük bir dosya, çünkü değişmeden çıkardı
    • -
    • - bir hasarın yanında expected: accept, çünkü hiçbir şey bunu karşılayamaz. Test edilen - sistemin dosyayı onarması amaçlanıyorsa sanitize, sorduğunuz soru buysa - unspecified yazın -
    • -
    -

    - Üçüncüsü önceden bilinemez. Bir hasar çalışıp hiçbir baytı oynatmazsa o dosya yazılmak yerine atılır - - çalıştırma sürer, hangi dosya olduğunu söyler ve kısmi çıkış koduyla biter. -

    -

    - Adım adım, bildirimi okuyan bir testle: test için bozuk dosya - nasıl yapılır. -

    -
    - -
    -

    Bir tarif nasıl görünür?

    -

    - Tarif, tüm bir çalıştırmayı anlatan bir YAML dosyasıdır. Testlerinizin yanına commit edin, - fixture'lar deponuzda ikili dosya olmaktan çıkar - herkes onları birkaç yüz karakterlik bir - dosyadan bayt bayt yeniden kurabilir. -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - Her target, size, size-range, boundary veya - contains anahtarlarından tam birine ihtiyaç duyar. İkisi hatadır, hiçbiri de öyle. - Geçersiz bir tarif hiç dosya yazmaz ve yalnızca ilkini değil tüm sorunları bir - seferde bildirir, her biri ilgili ayarı adlandırır. -

    -
    - -
    -

    Sistemimin bir dosyayla ne yapması gerektiğini nasıl bildiririm?

    -

    Sonuç yeterliyse kısa biçim, neden önemliyse uzun biçim:

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - Sonuçlar accept, reject, sanitize ve - unspecified. Nedenler, bir rapor onlara göre gruplayabilsin diye kapalı bir - listedir: content_malformed, count_limit, - dimensions_limit, duplicate, encoding_invalid, - extension_rule, filename_invalid, filename_too_long, - filename_traversal, malware_signature, mime_mismatch, - nesting_depth, none, size_limit ve - size_zero. -

    -

    - Bir neden söz konusu kuralı adlandırır, hükmü değil. Bu yüzden aynı neden iki - sonucun altında da durabilir - sınırın bir bayt altındaki dosya accept olur ve söz - konusu kural yine size_limit kalır. -

    -
    - -
    -

    Manifestte ne var?

    -

    - Her çalıştırmanın sonunda, kesilen çalıştırma dahil, dosyaların yanına yazılır. Dosya başına bir - girdi: -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "0.6.0-rc1" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - Çalıştırma bir tariften geldiyse bir recipe_hash, bir hazır ayardan geldiyse - overrides ile birlikte preset eklenir, böylece bir manifest her zaman - onu üreten şeye kadar izlenebilir. -

    -

    - Her girdi ayrıca dosyayı üreten tarifteki hedefin kimliği olan target_id taşır ve - summary.by_target her hedefin kaç dosyaya vardığını sayar. Birkaç hedefli bir tarif - böylece dosya adlarını okumadan hedef hedef denetlenebilir. -

    -
    - -
    -

    Hazır ayar nedir?

    -

    - Yaygın bir test sorusunu yanıtlayan hazır bir dosya seti, böylece seti kendiniz tasarlamanız - gerekmez. Hazır ayarlar altta sıradan tariflerdir ve eject tarifi yazdırır, oradan - düzenleyebilirsiniz. Her hazır ayarın genelde ne bulduğunu, sette ne olduğunu ve kabul ettiği - her ayarı anlatan kendi sayfası vardır. -

    +
    +

    Dokümantasyon sayfaları

    • -

      Boş ve asgari

      -

      Biçimin izin verdiği kadar küçük, geçerli bir dosya geçer mi?

      -

      empty-and-minimal

      +

      Kurulum EN

      +

      Windows, macOS veya Linux için indirin, arşivi doğrulayın ya da Docker, npm, pip veya Go ile kurun.

    • -
    • -

      Dosya adı işleme

      -

      Sistemim beklemediği bir dosya adını saklayıp gösterecek ve geri verecek mi?

      -

      filename-handling

      +
    • +

      Başlarken EN

      +

      Tam boyutta ilk dosya, sonra on bin dosya, doğrulanmış, silinmiş ve tarif olarak yazılmış.

    • -
    • -

      Resim boyutları

      -

      Sistemim ekranların ve platformların kullandığı boyutlardaki resimleri kabul ediyor mu?

      -

      picture-sizes

      +
    • +

      Komutlar EN

      +

      Her komut ve her seçenek varsayılan değeriyle, ve tüm çıkış kodları.

      +
    • +
    • +

      Tarif yazmak EN

      +

      Bir tarifin her anahtarı, boyutlar, dosya adları, beklenen tepkiler, bozmalar, arşivler ve hazır ayarlar.

    • -

      Boyut sınırları

      -

      Bir boyut sınırı tam bildirildiği yerde uygulanıyor mu?

      -

      size-boundaries

      +

      Tarif galerisi EN

      +

      Yüklemeler, içe aktarmalar, arşivler, e-posta, medya, CI ve toplu dosyalar için indirilmeye hazır tarifler.

      +
    • +
    • +

      Manifest EN

      +

      manifest.json dosyasının her alanı ve bir testin onu nasıl okuduğu.

    • -

      Tablo içe aktarma

      -

      Tablo içe aktarmam gerçek araçların dışa aktardıklarına dayanıyor mu?

      -

      tabular-import

      +

      Biçim ayarları EN

      +

      Her biçimin her ayarı, kabul ettiği değerler ve varsayılan değeriyle.

    • -

      Metin kodlaması

      -

      Okuyucum bir dosyanın hangi kodlamada olduğunu biliyor mu, yoksa tahmin mi ediyor?

      -

      text-encoding

      +

      Test çatıları EN

      +

      pytest, Playwright, Vitest ve node:test içindeki dosyalar.

      +
    • +
    • +

      Masaüstü uygulaması EN

      +

      Pencere, ekran ekran.

    • -

      Yükleme doğrulama

      -

      Yükleme formum alması gerekeni alıp geri kalanı reddediyor mu?

      -

      upload-validation

      +

      Araçlar

      +

      Elinizdeki dosyalar için çevrimdışı araçlar: bir arşivi açmanın güvenli olup olmadığı (zip slip, zip bomb) ve SHA-256 toplamlarını denetleme ya da yazma.

    -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show, seti kurmadan önce neye mal olacağını söyler ve bir sayının sizin sınırınız değil - bizim geçici değerimiz olduğunu açıkça belirtir. -

    -
    -

    Çıkış kodları ne anlama gelir?

    -

    - Her sonun kendi kodu vardır, makine tarafından okunabilir çıktı standart çıktıya gider ve başarısız - bir çalıştırma orada hiçbir şey yazdırmaz. Tablo dondurulmuş bir sözleşmedir - bir kodun - anlamını değiştirmek büyük sürüm artışı gerektirir. -

    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    KodAnlamı
    0Her şey çalıştı.
    1Araç içinde beklenmeyen bir hata.
    2Yanlış komut veya bayrak.
    3Tarif geçerli değil.
    4Biçim istenen şeyi yapamıyor.
    5Bir okuma veya yazma başarısız oldu.
    6Yeterli disk alanı yok.
    7verify bir uyuşmazlık buldu.
    8Çalıştırma bitti ama her şey üretilmedi.
    130Ctrl+C ile kesildi.
    143Bir sinyalle durduruldu, CI zaman aşımı böyle görünür.
    -
    -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - Ctrl+C ile durdurulan bir çalıştırma yine bir manifest bırakır ve asla yarım yazılmış bir dosya - bırakmaz, böylece iptal edilen bir işi bir sonraki temizleyebilir. -

    -

    - GitHub Actions ve GitLab CI için hazır iş akışları: CI - hattında test dosyaları nasıl üretilir. -

    +
    +

    Araç ne yapar, konu konu

    +
      +
    • +

      Biçimler

      +

      Üretilen tüm biçimler, her birinin mümkün olan en küçük dosyası ve kabul ettiği ayarlar. 32 biçimin hepsi kendi programında açılır.

      +
    • +
    • +

      Hazır ayarlar

      +

      Hazır test dosyası setleri, her biri tek bir test sorusunu yanıtlar: yükleme sınırları, dosya adları, kodlamalar, tablo içe aktarma, boş dosyalar ve doğrulama.

      +
    • +
    • +

      Bozuk dosyalar

      +

      Kasıtlı bozulmuş, tam boyutta bir dosya ve sisteminizin onu reddetmesi gerektiğini söyleyen bir bildirim. Yükleme doğrulaması ve ayrıştırıcıları sınamak için.

      +
    • +
    • +

      Örnek dosyalar

      +

      İndirilebilir test dosyaları: her biçimden 1 MB'lık birer dosya, bozuk PDF, Word ve Excel dosyaları, CSV tabloları ve yer tutucu resimler, hepsi SHA-256 ile.

      +
    • +
    • +

      Yükleme test senaryoları

      +

      Dosya yükleme test senaryoları: boyut sınırı, boş ve bozuk dosyalar, yanlış tür, beklenmedik dosya adları ve arşivler, her biri onu sınayan dosyayla birlikte.

      +
    • +
    • +

      CI'da test dosyaları

      +

      İkili dosya commit etmek yerine test dosyalarını hat içinde üretin: GitHub Actions iş akışı, GitLab işi, çıkış kodları ve PowerShell tuzağı.

      +
    • +
    • +

      Tam boyut

      +

      fsutil, dd, truncate ve mkfile, her biri kendi sisteminde ölçüldü, ve bir test PDF veya PNG gerektirdiğinde bu yolla yapılan dosyanın neden onlar olmadığı.

      +
    • +
    -
    -

    Masaüstü penceresi var mı?

    -

    - Evet, betiklenmeyen test için üzerine bir pencere konmuş aynı motor. Kırpılmış bir sürüm değildir: - bir test iki arayüzü yetenek yetenek karşılaştırır ve yalnızca birinin yapabildiği her şey - sessizce ayrışmak yerine bildirilip gerekçelendirilmelidir. -

    +
    +

    Hâlâ takıldınız mı?

    - Ekranlar tek bir grup, hazır ayarlar, aynı anda birkaç grup ve hakkında. Bir çalıştırmanın neye mal - olacağını bir şey yazmadan önce gösterir, çalışırken ilerlemeyi bildirir ve yarım yazılmış dosya - bırakmadan yarıda iptal edilebilir. Henüz bir tarif dosyası açmaz - tarifler şimdilik komut - satırının işidir ve pencere gruplarını formda kurar. + tfg <command> --help bir komutun ne aldığını terminalde gösterir. Her ret, ilgili ayarı, nedenini ve işe yarayacak bir değeri söyler. Bir şey buradaki bir sayfanın dediği gibi davranmıyorsa bildirin. Bu, sayfanın ya da programın bir hatasıdır.

    diff --git a/web/public/uk/docs/index.html b/web/public/uk/docs/index.html index 618d48f0..d2770031 100644 --- a/web/public/uk/docs/index.html +++ b/web/public/uk/docs/index.html @@ -147,387 +147,93 @@

    Документація

    - Усе, що робить інструмент, розкладено за питаннями, з якими люди справді приходять. - README у репозиторії - повний довідник, і він завжди відповідає - завантаженій вами збірці. + Як встановити tfg, створити перші тестові файли, і все, що програма приймає та записує: кожна команда й кожен прапорець, кожен ключ рецепта, кожне поле маніфесту та кожне налаштування кожного формату. Ці сторінки англійською, бо вони створюються із самої програми під час кожного збирання сайту і тому завжди кажуть те, що робить версія, яку ви завантажуєте.

    -
    -

    Які є команди?

    -

    Кожна робить одну справу:

    -
    tfg generate    створити файли за рецептом або за прапорцями
    -tfg validate    перевірити рецепт, нічого не записуючи
    -tfg verify      звірити каталог із маніфестом
    -tfg cleanup     видалити файли, перелічені в маніфесті
    -tfg recipe fmt  вивести рецепт у усталеному вигляді
    -tfg preset      зібрати набір файлів за іменованим тестовим питанням
    -tfg formats     перелічити формати цієї збірки
    -tfg damage      перелічити способи, якими ця збірка може навмисно зіпсувати файл
    -tfg tool        невеликі інструменти для вже наявних файлів
    -tfg version     вивести версію інструмента
    -tfg license     вивести ліцензію та що вона означає для створених файлів
    -

    - У tfg tool зібрано інструменти для наявних файлів, наприклад перевірку архіву перед - розпакуванням. На сторінці Інструменти описано кожен із них. -

    -
    - -
    -

    Як створити один файл точного розміру?

    -

    - Укажіть формат, розмір і місце призначення. Розміри рахуються по 1024, тому 2mb - це - 2097152 байти. Підійде й просте число байтів, тож --size 10485761 запитує рівно - стільки. -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    Корисні прапорці команди generate:

    -
    - - - - - - - - - - - - - - - - - -
    ПрапорецьЩо робить
    --format <id>формат файлів, наприклад txt
    --size <size>точний розмір кожного файлу, наприклад 10mb або просте число байтів
    --size-range <a-b>розмір, що вибирається для кожного файлу з діапазону, наприклад 1kb-8kb. Вибір іде від seed
    --boundary <size>три файли навколо ліміту: на байт менше, сам ліміт, на байт більше
    --count <n>скільки файлів створити. За замовчуванням 1
    --name <template>шаблон імені, наприклад invoice_{index:04}.txt
    --out <dir>каталог, у який записувати
    --seed <n>seed запуску. Той самий seed дає ті самі байти
    --set <k>=<v>налаштування формату, можна повторювати
    --damage <name>навмисно зіпсувати файли, можна повторювати, застосовується по порядку. Список виводить tfg damage
    --expected <outcome>accept, reject, sanitize або unspecified
    --dry-runпорахувати й показати, нічого не записуючи
    --jsonзаписати маніфест у стандартний вивід
    -
    -
    - -
    -

    Як зробити навмисно зламаний файл?

    -

    - Будь-який інший файл, що його записує цей інструмент, коректний за побудовою, і це відповідає на два - з трьох питань, які ставить перевірка завантаження. --damage відповідає на третє - - чи відкривається файл узагалі. Файл створюється як зазвичай, а потім псується, тому в нього - лишається запитаний розмір. -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - Налаштування вказуються після двокрапки. Прапорець можна повторювати, і порядок запису - це порядок - застосування. tfg damage перелічує, що вміє ця збірка та що приймає кожен вид - пошкодження. -

    -

    У рецепті ключ - це список імен або налаштувань:

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - Пошкоджений файл отримує в маніфесті expected: reject із записаним поруч пошкодженням. - Дві речі відхиляються до запису чого-небудь, бо кожна залишила б на диску файл, неправильно - описаний маніфестом: -

    -
      -
    • файл менший, ніж потрібно пошкодженню, бо він вийшов би без змін
    • -
    • - expected: accept поруч із пошкодженням, бо цьому не міг би відповідати жоден файл. - Пишіть sanitize, якщо тестована система має полагодити файл, або - unspecified, якщо саме це питання ви й ставите -
    • -
    -

    - Третє наперед дізнатися не можна. Якщо пошкодження виконується й не змінює жодного байта, такий файл - відкидається, а не записується - запуск триває, повідомляє, що це був за файл, і завершується - кодом часткового завершення. -

    -

    - Крок за кроком, з тестом, який читає маніфест: як зробити - пошкоджений файл для тестів. -

    -
    - -
    -

    Як виглядає рецепт?

    -

    - Рецепт - це файл YAML, що описує цілий запуск. Закомітьте його поряд із тестами, і фікстури - перестануть бути бінарними файлами у вашому репозиторії - будь-хто зможе відтворити їх байт у - байт із файлу в кілька сотень символів. -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - Кожній цілі потрібен рівно один із ключів size, size-range, - boundary або contains. Два - це помилка, і жодного - теж. Недійсний - рецепт записує жодного файлу і повідомляє про всі проблеми одразу, а не лише - про першу, щоразу називаючи налаштування, якого вона стосується. -

    -
    - -
    -

    Як оголосити, що моя система має робити з файлом?

    -

    Коротка форма, коли досить результату, і довга, коли важлива причина:

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - Результати - accept, reject, sanitize і - unspecified. Причини утворюють закритий список, щоб звіт міг за ними групувати: - content_malformed, count_limit, dimensions_limit, - duplicate, encoding_invalid, extension_rule, - filename_invalid, filename_too_long, filename_traversal, - malware_signature, mime_mismatch, nesting_depth, - none, size_limit і size_zero. -

    -

    - Причина називає чинне правило, а не вердикт. Тому та сама причина може стояти під - будь-яким результатом - файл на байт менший за ліміт отримує accept, а правило, про - яке йдеться, усе одно size_limit. -

    -
    - -
    -

    Що в маніфесті?

    -

    - Він записується поряд із файлами наприкінці кожного запуску, зокрема й перерваного. Один запис на - файл: -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "0.6.0-rc1" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - recipe_hash додається, якщо запуск був за рецептом, а preset з - overrides - якщо за пресетом, тож маніфест завжди можна простежити до того, що його - створило. -

    -

    - Кожен запис також містить target_id - id цілі рецепта, що створила файл, а - summary.by_target рахує файли кожної цілі. Рецепт із кількома цілями можна тому - перевірити ціль за ціллю, не читаючи імена файлів. -

    -
    - -
    -

    Що таке пресет?

    -

    - Готовий набір файлів, що відповідає на поширене тестове питання, щоб вам не доводилося проєктувати - набір самостійно. Пресети - звичайні рецепти всередині, а eject виводить рецепт, - щоб ви могли його відредагувати. Кожен пресет має окрему сторінку про - те, що він зазвичай знаходить, що входить у набір і які налаштування приймає. -

    +
    +

    Сторінки документації

    • -

      Порожні та мінімальні

      -

      Чи пройде коректний файл, настільки малий, наскільки дозволяє формат?

      -

      empty-and-minimal

      +

      Встановлення EN

      +

      Завантажити для Windows, macOS або Linux, перевірити архів або встановити через Docker, npm, pip чи Go.

    • -
    • -

      Обробка імен файлів

      -

      Чи збереже, покаже та поверне моя система ім'я файлу, якого не очікувала?

      -

      filename-handling

      +
    • +

      Перші кроки EN

      +

      Перший файл точного розміру, потім десять тисяч, перевірені, видалені та записані як рецепт.

    • -
    • -

      Розміри зображень

      -

      Чи приймає моя система зображення тих розмірів, які використовують екрани й платформи?

      -

      picture-sizes

      +
    • +

      Команди EN

      +

      Кожна команда й кожен прапорець зі значенням за замовчуванням, і всі коди завершення.

      +
    • +
    • +

      Як писати рецепти EN

      +

      Кожен ключ рецепта, розміри, імена файлів, очікувані реакції, пошкодження, архіви та пресети.

    • -

      Межі розміру

      -

      Чи застосовується ліміт розміру саме там, де його оголошено?

      -

      size-boundaries

      +

      Галерея рецептів EN

      +

      Готові рецепти для завантаження: вивантаження, імпорт, архіви, пошта, медіа, CI та масові файли.

      +
    • +
    • +

      Маніфест EN

      +

      Кожне поле manifest.json і те, як його читає тест.

    • -

      Імпорт таблиць

      -

      Чи переживе мій імпорт таблиць те, що експортують справжні інструменти?

      -

      tabular-import

      +

      Налаштування форматів EN

      +

      Кожне налаштування кожного формату з допустимими значеннями та значенням за замовчуванням.

    • -

      Кодування тексту

      -

      Чи знає мій читач, у якому кодуванні файл, чи вгадує?

      -

      text-encoding

      +

      Тестові фреймворки EN

      +

      Файли всередині pytest, Playwright, Vitest і node:test.

      +
    • +
    • +

      Настільний застосунок EN

      +

      Вікно програми, екран за екраном.

    • -

      Перевірка завантаження

      -

      Чи приймає моя форма завантаження те, що має, і відхиляє решту?

      -

      upload-validation

      +

      Інструменти

      +

      Офлайн-інструменти для наявних файлів: чи безпечно розпаковувати архів, зокрема zip slip і zip-бомби, а також перевірка й запис контрольних сум SHA-256.

    -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show повідомляє, скільки коштував би набір, перш ніж ви його зберете, і прямо каже, - коли число - наша тимчасова підстановка, а не ваш ліміт. -

    -
    -

    Що означають коди завершення?

    -

    - Кожен кінець має власний код, машиночитний вивід іде в стандартний вивід, а невдалий запуск нічого - туди не друкує. Таблиця - заморожений контракт: зміна значення коду вимагає підвищення мажорної - версії. -

    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    КодЗначення
    0Усе спрацювало.
    1Непередбачена помилка всередині інструмента.
    2Неправильна команда або прапорець.
    3Рецепт недійсний.
    4Формат не може зробити те, що просили.
    5Не вдалося прочитати або записати.
    6Недостатньо місця на диску.
    7verify виявив розбіжність.
    8Запуск завершено, але створено не все.
    130Перервано за допомогою Ctrl+C.
    143Зупинено сигналом, так виглядає тайм-аут у CI.
    -
    -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - Запуск, зупинений за допомогою Ctrl+C, усе одно залишає маніфест і ніколи не залишає наполовину - записаного файлу, тож скасоване завдання може бути прибране наступним. -

    -

    - Готові workflow для GitHub Actions і GitLab CI: як генерувати - тестові файли в конвеєрі CI. -

    +
    +

    Що робить інструмент, за темами

    +
      +
    • +

      Формати

      +

      Усі формати, які створює генератор, найменший можливий файл кожного та допустимі налаштування. Усі 32 відкриваються у своїх програмах.

      +
    • +
    • +

      Пресети

      +

      Готові набори тестових файлів, кожен відповідає на одне питання: ліміти завантаження, імена файлів, кодування, імпорт таблиць, порожні файли та перевірка завантаження.

      +
    • +
    • +

      Пошкоджені файли

      +

      Навмисно зіпсований файл точного розміру з маніфестом, який каже, що ваша система має його відхилити. Для перевірки валідації завантаження та парсерів.

      +
    • +
    • +

      Приклади файлів

      +

      Тестові файли для завантаження: по одному кожного формату по 1 МБ, пошкоджені PDF, Word і Excel, таблиці CSV і зображення-заповнювачі, кожен із сумою SHA-256.

      +
    • +
    • +

      Тест-кейси завантаження

      +

      Тест-кейси для завантаження файлів: ліміт розміру, порожні й пошкоджені файли, неправильний тип, несподівані імена та архіви, у кожного свій файл для перевірки.

      +
    • +
    • +

      Тестові файли в CI

      +

      Генеруйте тестові файли в конвеєрі, а не комітьте бінарники: workflow GitHub Actions, завдання GitLab, коди завершення та пастка PowerShell.

      +
    • +
    • +

      Точний розмір

      +

      fsutil, dd, truncate і mkfile, кожну команду виміряно у своїй системі, і чому такий файл не є PDF чи PNG, коли тесту потрібен справжній.

      +
    • +
    -
    -

    Чи є десктопне вікно?

    -

    - Так, той самий рушій із вікном згори, для тестування, яке не автоматизується. Це не урізана версія: - тест порівнює два інтерфейси можливість за можливістю, і все, що вміє лише один із них, має бути - оголошене й обґрунтоване, а не тихо розходитися. -

    +
    +

    Досі не виходить?

    - Екрани: одна партія, пресети, кілька партій одночасно та про програму. Вікно показує, скільки - коштував би запуск, перш ніж щось записати, відображає перебіг роботи й може бути скасоване на - півдорозі без наполовину записаного файлу. Файл рецепта воно поки не відкриває - рецепти поки - справа командного рядка, а вікно збирає свої партії у формі. + tfg <command> --help показує в терміналі, що приймає команда. Кожна відмова називає налаштування, якого вона стосується, причину та значення, яке підійде. Якщо щось працює не так, як сказано на сторінці, повідомте про це. Це помилка сторінки або програми.

    diff --git a/web/public/uk/tools/index.html b/web/public/uk/tools/index.html index 3230d814..6d8b3816 100644 --- a/web/public/uk/tools/index.html +++ b/web/public/uk/tools/index.html @@ -151,6 +151,21 @@
    +

    Документація

    Перевірка архіву перед розпакуванням і звірка контрольних сум

    diff --git a/web/public/vi/cong-cu/index.html b/web/public/vi/cong-cu/index.html index 1181ebad..e694f2a2 100644 --- a/web/public/vi/cong-cu/index.html +++ b/web/public/vi/cong-cu/index.html @@ -151,6 +151,21 @@

    +

    Tài liệu

    Kiểm tra tệp nén trước khi giải nén và xác minh checksum

    diff --git a/web/public/vi/tai-lieu/index.html b/web/public/vi/tai-lieu/index.html index 4b3350c3..ca856df3 100644 --- a/web/public/vi/tai-lieu/index.html +++ b/web/public/vi/tai-lieu/index.html @@ -147,381 +147,93 @@

    Tài liệu

    - Mọi thứ công cụ làm, sắp xếp theo những câu hỏi mà mọi người thật sự mang đến. - README trong kho mã là tài liệu tham chiếu đầy đủ và luôn khớp với - bản dựng bạn đã tải. + Cách cài đặt tfg, tạo những tệp kiểm thử đầu tiên, và mọi thứ chương trình nhận và ghi: mọi lệnh và mọi tùy chọn, mọi khóa của công thức, mọi trường của manifest và mọi thiết lập của mọi định dạng. Các trang này bằng tiếng Anh, vì chúng được tạo từ chính chương trình mỗi lần dựng trang web, nên luôn nói đúng những gì phiên bản bạn tải về làm.

    -
    -

    Có những lệnh nào?

    -

    Mỗi lệnh làm đúng một việc:

    -
    tfg generate    tạo tệp, từ công thức hoặc từ các cờ
    -tfg validate    kiểm tra công thức và không ghi gì cả
    -tfg verify      kiểm tra một thư mục đối chiếu với manifest
    -tfg cleanup     xóa các tệp mà manifest liệt kê
    -tfg recipe fmt  in công thức ở dạng chuẩn hóa
    -tfg preset      dựng một bộ tệp từ một câu hỏi kiểm thử có tên
    -tfg formats     liệt kê các định dạng bản dựng này hỗ trợ
    -tfg damage      liệt kê các cách bản dựng này có thể cố ý làm hỏng một tệp
    -tfg tool        các tiện ích nhỏ cho tệp bạn đã có
    -tfg version     in phiên bản công cụ
    -tfg license     in giấy phép và ý nghĩa của nó với tệp được tạo
    -

    - tfg tool chứa các công cụ cho tệp bạn đã có, chẳng hạn kiểm tra một tệp nén trước khi - giải nén. Công cụ mô tả từng công cụ. -

    -
    - -
    -

    Làm sao tạo một tệp đơn có kích thước chính xác?

    -

    - Nêu định dạng, kích thước và nơi đặt. Kích thước đếm theo 1024, nên 2mb là 2097152 - byte. Số byte thuần cũng được, nên --size 10485761 yêu cầu đúng chừng đó. -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    Các cờ hữu ích của generate:

    -
    - - - - - - - - - - - - - - - - - -
    CờTác dụng
    --format <id>định dạng của các tệp, ví dụ txt
    --size <size>kích thước chính xác của mỗi tệp, như 10mb hoặc số byte thuần
    --size-range <a-b>kích thước rút cho từng tệp từ một khoảng, như 1kb-8kb. Lần rút lấy từ seed
    --boundary <size>ba tệp quanh một giới hạn: thấp hơn một byte, đúng giới hạn, cao hơn một byte
    --count <n>tạo bao nhiêu tệp. Mặc định 1
    --name <template>mẫu tên, ví dụ invoice_{index:04}.txt
    --out <dir>thư mục để ghi vào
    --seed <n>seed của lần chạy. Cùng seed cho cùng các byte
    --set <k>=<v>một thiết lập định dạng, lặp lại được
    --damage <name>cố ý làm hỏng tệp, lặp lại được và áp dụng theo thứ tự. Chạy tfg damage để xem danh sách
    --expected <outcome>accept, reject, sanitize hoặc unspecified
    --dry-runđếm và hiển thị, hoàn toàn không ghi gì
    --jsonghi manifest ra đầu ra chuẩn
    -
    -
    - -
    -

    Làm sao tạo một tệp cố ý bị hỏng?

    -

    - Mọi tệp khác mà công cụ này ghi đều đúng theo cách xây dựng, điều đó trả lời hai trong ba câu hỏi mà - trình kiểm tra tải lên đặt ra. --damage trả lời câu thứ ba - tệp có mở được không. - Tệp được tạo bình thường rồi bị làm hỏng, nên nó vẫn có kích thước bạn đã yêu cầu. -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - Các thiết lập đặt sau dấu hai chấm. Cờ lặp lại được, và thứ tự bạn viết là thứ tự chúng được áp - dụng. tfg damage liệt kê những gì bản dựng này làm được và mỗi kiểu nhận gì. -

    -

    Trong công thức, khóa là một danh sách, gồm tên hoặc thiết lập:

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - Tệp bị làm hỏng nhận expected: reject trong manifest, kèm kiểu hỏng được ghi bên cạnh. - Hai thứ bị từ chối trước khi ghi bất cứ gì, vì mỗi thứ sẽ đặt lên đĩa một tệp mà manifest mô tả - sai: -

    -
      -
    • tệp nhỏ hơn mức kiểu hỏng cần, vì nó sẽ ra mà không thay đổi
    • -
    • - expected: accept bên cạnh một kiểu hỏng, vì không gì có thể đáp ứng. Hãy viết - sanitize nếu hệ thống được kiểm thử phải sửa tệp, hoặc unspecified - nếu đó chính là câu hỏi bạn đang đặt -
    • -
    -

    - Thứ ba không thể biết trước. Nếu một kiểu hỏng chạy mà không đổi byte nào, tệp đó bị bỏ thay vì được - ghi - lần chạy tiếp tục, nói đó là tệp nào và kết thúc bằng mã thoát một phần. -

    -

    - Từng bước, với một bài kiểm thử đọc manifest: cách tạo tệp bị - hỏng để kiểm thử. -

    -
    - -
    -

    Một công thức trông thế nào?

    -

    - Công thức là một tệp YAML mô tả cả một lần chạy. Hãy commit nó bên cạnh các bài kiểm thử và fixture - thôi là tệp nhị phân trong kho mã - ai cũng có thể dựng lại chúng, từng byte, từ một tệp vài - trăm ký tự. -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - Mỗi target cần đúng một trong size, size-range, boundary hoặc - contains. Hai cái là lỗi và không cái nào cũng là lỗi. Công thức không hợp lệ ghi - không tệp nào và báo mọi vấn đề cùng lúc thay vì chỉ cái đầu, mỗi cái nêu thiết - lập mà nó nói đến. -

    -
    - -
    -

    Làm sao khai báo hệ thống của tôi cần làm gì với một tệp?

    -

    Dạng ngắn khi kết quả là đủ, dạng dài khi lý do quan trọng:

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - Các kết quả là accept, reject, sanitize và - unspecified. Các lý do là một danh sách đóng để báo cáo có thể nhóm theo chúng: - content_malformed, count_limit, dimensions_limit, - duplicate, encoding_invalid, extension_rule, - filename_invalid, filename_too_long, filename_traversal, - malware_signature, mime_mismatch, nesting_depth, - none, size_limit và size_zero. -

    -

    - Một lý do nêu quy tắc đang áp dụng, không phải phán quyết. Vì vậy cùng một lý do có - thể nằm dưới cả hai kết quả - tệp thấp hơn giới hạn một byte là accept, và quy tắc - liên quan vẫn là size_limit. -

    -
    - -
    -

    Manifest chứa gì?

    -

    - Nó được ghi bên cạnh các tệp ở cuối mỗi lần chạy, kể cả lần chạy bị ngắt. Một mục cho mỗi tệp: -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "0.6.0-rc1" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - recipe_hash được thêm khi lần chạy đến từ một công thức, và preset cùng - overrides khi nó đến từ một preset, nên manifest luôn truy ngược được về thứ đã tạo - ra nó. -

    -

    - Mỗi mục còn mang target_id, id của target trong công thức đã tạo tệp, và - summary.by_target đếm số tệp mà mỗi target tạo ra. Một công thức có nhiều target - nhờ vậy kiểm tra được từng target mà không cần đọc tên tệp. -

    -
    - -
    -

    Preset là gì?

    -

    - Một bộ tệp dựng sẵn trả lời một câu hỏi kiểm thử thường gặp, để bạn không phải tự thiết kế bộ. - Preset thực chất là công thức bình thường, và eject in công thức ra để bạn chỉnh - sửa từ đó. Mỗi preset có trang riêng nói nó thường tìm thấy gì, trong - bộ có gì và mọi thiết lập nó nhận. -

    +
    +

    Các trang tài liệu

    • -

      Rỗng và tối thiểu

      -

      Một tệp hợp lệ và nhỏ nhất mà định dạng cho phép có qua được không?

      -

      empty-and-minimal

      +

      Cài đặt EN

      +

      Tải về cho Windows, macOS hoặc Linux, kiểm tra tệp nén, hoặc cài bằng Docker, npm, pip hay Go.

    • -
    • -

      Xử lý tên tệp

      -

      Hệ thống của tôi có lưu, hiển thị và trả lại một tên tệp mà nó không ngờ tới không?

      -

      filename-handling

      +
    • +

      Bắt đầu EN

      +

      Tệp đầu tiên đúng kích thước, rồi mười nghìn tệp, được kiểm tra, xóa đi và ghi lại thành công thức.

    • -
    • -

      Kích thước hình ảnh

      -

      Hệ thống của tôi có nhận hình ảnh ở các kích thước mà màn hình và nền tảng dùng không?

      -

      picture-sizes

      +
    • +

      Lệnh EN

      +

      Mọi lệnh và mọi tùy chọn cùng giá trị mặc định, và mọi mã thoát.

      +
    • +
    • +

      Viết công thức EN

      +

      Mọi khóa của công thức, kích thước, tên tệp, phản ứng mong đợi, hư hỏng, tệp nén và preset.

    • -

      Ranh giới kích thước

      -

      Giới hạn kích thước có được áp dụng đúng nơi nó được khai báo không?

      -

      size-boundaries

      +

      Thư viện công thức EN

      +

      Công thức sẵn để tải cho tải lên, nhập dữ liệu, tệp nén, email, đa phương tiện, CI và tệp số lượng lớn.

      +
    • +
    • +

      Manifest EN

      +

      Mọi trường của manifest.json và cách một bài kiểm thử đọc nó.

    • -

      Nhập bảng

      -

      Việc nhập bảng của tôi có chịu được những gì công cụ thật xuất ra không?

      -

      tabular-import

      +

      Thiết lập định dạng EN

      +

      Mọi thiết lập của mọi định dạng, với các giá trị được chấp nhận và giá trị mặc định.

    • -

      Mã hóa văn bản

      -

      Trình đọc của tôi có biết tệp ở mã hóa nào, hay chỉ đoán?

      -

      text-encoding

      +

      Framework kiểm thử EN

      +

      Các tệp bên trong pytest, Playwright, Vitest và node:test.

      +
    • +
    • +

      Ứng dụng máy tính EN

      +

      Cửa sổ chương trình, từng màn hình một.

    • -

      Kiểm tra tải lên

      -

      Biểu mẫu tải lên của tôi có nhận đúng thứ nó cần và từ chối phần còn lại không?

      -

      upload-validation

      +

      Công cụ

      +

      Công cụ ngoại tuyến cho tệp bạn đã có: xem một tệp nén có an toàn để giải nén không, gồm cả zip slip và zip bomb, và kiểm tra hoặc ghi checksum SHA-256.

    -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show cho bạn biết bộ sẽ tốn bao nhiêu trước khi dựng, và nói thẳng khi một con số là - giá trị tạm của chúng tôi chứ không phải giới hạn của bạn. -

    -
    -

    Các mã thoát có nghĩa gì?

    -

    - Mỗi kết cục có mã riêng, đầu ra máy đọc được đi ra đầu ra chuẩn, và lần chạy thất bại không in gì ở - đó. Bảng này là một hợp đồng đóng băng - đổi nghĩa của một mã đòi hỏi tăng phiên bản chính. -

    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    MãÝ nghĩa
    0Mọi thứ đều chạy tốt.
    1Lỗi bất ngờ bên trong công cụ.
    2Lệnh hoặc cờ sai.
    3Công thức không hợp lệ.
    4Định dạng không làm được điều được yêu cầu.
    5Đọc hoặc ghi thất bại.
    6Không đủ dung lượng đĩa.
    7verify phát hiện sai lệch.
    8Lần chạy đã xong nhưng không phải mọi thứ đều được tạo.
    130Bị ngắt bằng Ctrl+C.
    143Bị dừng bởi một tín hiệu, đó là hình dạng của việc CI hết thời gian.
    -
    -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - Lần chạy bị dừng bằng Ctrl+C vẫn để lại manifest và không bao giờ để lại tệp ghi dở, nên tác vụ bị - hủy vẫn có thể được dọn bởi tác vụ sau. -

    -

    - Workflow có sẵn cho GitHub Actions và GitLab CI: cách tạo tệp - kiểm thử trong pipeline CI. -

    +
    +

    Công cụ làm gì, theo từng chủ đề

    +
      +
    • +

      Định dạng

      +

      Mọi định dạng tệp mà trình tạo này tạo ra, tệp nhỏ nhất có thể của mỗi định dạng và các thiết lập nó nhận. Cả 32 đều mở được bằng phần mềm của chúng.

      +
    • +
    • +

      Preset

      +

      Các bộ tệp kiểm thử dựng sẵn, mỗi bộ trả lời một câu hỏi kiểm thử: giới hạn tải lên, tên tệp, mã hóa, nhập bảng, tệp rỗng và kiểm tra hợp lệ.

      +
    • +
    • +

      Tệp bị hỏng

      +

      Một tệp cố ý làm hỏng, đúng kích thước, với manifest nói hệ thống của bạn phải từ chối nó. Để kiểm thử xác thực tải lên và trình phân tích cú pháp.

      +
    • +
    • +

      Tệp mẫu

      +

      Tải xuống tệp mẫu để kiểm thử: mỗi định dạng một tệp 1 MB, tệp PDF, Word và Excel bị hỏng, bảng CSV và ảnh giữ chỗ, mỗi tệp kèm mã SHA-256.

      +
    • +
    • +

      Kiểm thử tải lên

      +

      Các trường hợp kiểm thử tải tệp lên: giới hạn kích thước, tệp rỗng và tệp hỏng, sai loại tệp, tên tệp bất ngờ và tệp nén, mỗi trường hợp kèm tệp kiểm thử nó.

      +
    • +
    • +

      Tệp kiểm thử trong CI

      +

      Tạo tệp kiểm thử trong pipeline thay vì commit tệp nhị phân: workflow GitHub Actions, job GitLab, mã thoát và cái bẫy của PowerShell.

      +
    • +
    • +

      Kích thước chính xác

      +

      fsutil, dd, truncate và mkfile, mỗi lệnh được đo trên hệ thống của nó, và vì sao tệp tạo kiểu đó không phải PDF hay PNG khi bài kiểm thử cần.

      +
    • +
    -
    -

    Có cửa sổ desktop không?

    -

    - Có, cùng một động cơ với một cửa sổ phủ lên, cho kiểu kiểm thử không viết kịch bản. Nó không phải - bản cắt giảm: một bài kiểm thử so sánh hai giao diện từng khả năng một, và bất cứ điều gì chỉ - một bên làm được đều phải được khai báo và biện minh thay vì lặng lẽ lệch nhau. -

    +
    +

    Vẫn còn vướng?

    - Các màn hình là một lô, preset, nhiều lô cùng lúc và giới thiệu. Nó cho biết một lần chạy sẽ tốn bao - nhiêu trước khi ghi gì, báo tiến độ khi đang chạy và có thể hủy giữa chừng mà không để lại tệp - ghi dở. Nó chưa mở được tệp công thức - hiện công thức là việc của dòng lệnh, còn cửa sổ dựng - các lô trong biểu mẫu. + tfg <command> --help cho biết trong terminal một lệnh nhận những gì. Mỗi lần từ chối đều nêu thiết lập liên quan, lý do và một giá trị sẽ dùng được. Nếu điều gì đó không hoạt động như một trang ở đây nói, hãy báo cho chúng tôi. Đó là lỗi của trang hoặc của chương trình.

    diff --git a/web/public/zh-hans/docs/index.html b/web/public/zh-hans/docs/index.html index 9a57b07c..5ac8db32 100644 --- a/web/public/zh-hans/docs/index.html +++ b/web/public/zh-hans/docs/index.html @@ -147,350 +147,93 @@

    文档

    - 工具的全部功能,按人们实际会问的问题来组织。仓库中的 README 是完整参考,并且始终与你下载的版本一致。 + 如何安装 tfg、生成第一批测试文件,以及程序接收和写出的一切:每个命令和每个参数、配方的每个键、清单的每个字段、每种格式的每个设置。这些页面是英文的,因为它们在每次构建网站时都由程序本身生成,所以始终与你下载的版本一致。

    -
    -

    有哪些命令?

    -

    每个命令只做一件事:

    -
    tfg generate    根据配方或参数生成文件
    -tfg validate    检查配方,不写入任何内容
    -tfg verify      对照清单检查目录
    -tfg cleanup     删除清单中列出的文件
    -tfg recipe fmt  以规范形式打印配方
    -tfg preset      根据具名测试问题构建一组文件
    -tfg formats     列出此版本支持的格式
    -tfg damage      列出此版本可以故意破坏文件的方式
    -tfg tool        处理现有文件的小工具
    -tfg version     打印工具版本
    -tfg license     打印许可证及其对生成文件的含义
    -

    - tfg tool 包含处理现有文件的工具,例如在解压前检查压缩包。工具介绍了其中每一个。 -

    -
    - -
    -

    如何生成一个大小精确的文件?

    -

    - 指定格式、大小和输出位置。大小按 1024 进制计算,所以 2mb 是 2097152 字节。直接写字节数也可以,所以 --size - 10485761 请求的就是恰好这么多。 -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    generate 常用的参数:

    -
    - - - - - - - - - - - - - - - - - -
    参数作用
    --format <id>文件格式,例如 txt
    --size <size>每个文件的精确大小,例如 10mb 或直接写字节数
    --size-range <a-b>从范围内为每个文件抽取一个大小,例如 1kb-8kb。抽取结果来自种子
    --boundary <size>围绕一个限制的三个文件:小一字节、恰好等于限制、大一字节
    --count <n>生成多少个文件。默认 1
    --name <template>文件名模板,例如 invoice_{index:04}.txt
    --out <dir>写入的目录
    --seed <n>本次运行的种子。相同的种子得到相同的字节
    --set <k>=<v>一项格式设置,可重复使用
    --damage <name>故意破坏文件,可重复使用,并按顺序应用。运行 tfg damage 查看列表
    --expected <outcome>accept、reject、sanitize 或 unspecified
    --dry-run只统计并显示,完全不写入
    --json将清单写到标准输出
    -
    -
    - -
    -

    如何做一个故意损坏的文件?

    -

    - 本工具写出的其他所有文件在构造上都是正确的,这回答了上传校验器会问的三个问题中的两个。--damage - 回答第三个,也就是文件到底能不能打开。文件先正常生成,再被破坏,因此仍然保持你请求的大小。 -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - 设置写在冒号后面。该参数可以重复,写入的顺序就是应用的顺序。tfg damage 会列出此版本能做什么,以及每种破坏接受哪些设置。 -

    -

    在配方中,这个键是一个列表,内容是名称或设置:

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - 受损文件在清单中会得到 expected: reject,并在旁边记录所做的破坏。有两种情况会在写入任何内容之前被拒绝,因为各自都会在磁盘上留下清单描述有误的文件: -

    -
      -
    • 文件小于破坏所需的大小,因为它会原样输出
    • -
    • - 在破坏旁边写 expected: accept,因为没有任何文件能满足它。如果被测系统应该修复该文件,请写 - sanitize,如果你问的正是这个问题,请写 unspecified -
    • -
    -

    - 第三种无法提前得知。如果某个破坏运行后没有改动任何字节,该文件会被丢弃而不是写出,运行会继续,指出是哪个文件,并以部分完成的退出码结束。 -

    -

    - 一步一步来,附带一个读取清单的测试:如何制作用于测试的损坏文件。 -

    -
    - -
    -

    配方是什么样子?

    -

    - 配方是一个描述整次运行的 YAML 文件。把它与测试放在一起提交,fixture 就不再是仓库里的二进制文件,任何人都可以用一个只有几百个字符的文件逐字节重建它们。 -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - 每个 target 必须恰好有 size、size-range、boundary 或 - contains - 中的一个。两个是错误,一个都没有也是错误。无效的配方不会写入任何文件,并且会一次报告所有问题,而不是只报第一个,每个问题都会指明所涉及的设置。 -

    -
    - -
    -

    如何声明我的系统应如何处理某个文件?

    -

    只需结果时用短写法,原因重要时用长写法:

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - 结果有 accept、reject、sanitize 和 - unspecified。原因是封闭列表,便于报告按原因分组:content_malformed、count_limit、dimensions_limit、duplicate、encoding_invalid、extension_rule、filename_invalid、filename_too_long、filename_traversal、malware_signature、mime_mismatch、nesting_depth、none、size_limit - 和 size_zero。 -

    -

    - 原因指明的是起作用的规则,而不是裁决。所以同一个原因可以出现在两种结果之下:比限制小一字节的文件是 accept,而它所涉及的规则仍然是 - size_limit。 -

    -
    - -
    -

    清单里有什么?

    -

    - 每次运行结束时,包括被中断的运行,它都会写在文件旁边。每个文件一项: -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "0.6.0-rc1" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - 运行来自配方时会加上 recipe_hash,来自预设时会加上 preset 和 - overrides,因此清单总能追溯到产生它的来源。 -

    -

    - 每一项还带有 target_id,即配方中生成该文件的 target 的 id,summary.by_target 则统计每个 target - 生成的文件数。因此有多个 target 的配方可以逐个 target 检查,无需阅读文件名。 -

    -
    - -
    -

    什么是预设?

    -

    - 预设是回答常见测试问题的现成文件集,你不必自己设计。预设底层就是普通配方,eject - 会把配方打印出来,供你从那里开始编辑。每个预设都有自己的页面,说明它通常能发现什么、集合里有什么,以及它接受的每项设置。 -

    +
    +

    文档页面

    • -

      空文件与最小文件

      -

      一个合法且达到格式允许的最小大小的文件能通过吗?

      -

      empty-and-minimal

      +

      安装 EN

      +

      下载适用于 Windows、macOS 或 Linux 的版本并校验压缩包,或通过 Docker、npm、pip、Go 安装。

    • -
    • -

      文件名处理

      -

      我的系统能否正确保存、显示并返回它没料到的文件名?

      -

      filename-handling

      +
    • +

      入门 EN

      +

      先生成一个精确大小的文件,再生成一万个,校验、删除,并写成配方。

    • -
    • -

      图片尺寸

      -

      我的系统能接受屏幕和平台所用尺寸的图片吗?

      -

      picture-sizes

      +
    • +

      命令 EN

      +

      每个命令和每个参数及其默认值,以及所有退出码。

      +
    • +
    • +

      编写配方 EN

      +

      配方的每个键、大小、文件名、预期反应、损坏、压缩包和预设。

    • -

      大小边界

      -

      大小限制是否恰好在声明的位置生效?

      -

      size-boundaries

      +

      配方库 EN

      +

      可直接下载的配方,用于上传、导入、压缩包、邮件、媒体、CI 和大量文件。

      +
    • +
    • +

      清单 EN

      +

      manifest.json 的每个字段,以及测试如何读取它。

    • -

      表格导入

      -

      我的表格导入能应付真实工具导出的内容吗?

      -

      tabular-import

      +

      格式设置 EN

      +

      每种格式的每个设置,包括可接受的值和默认值。

    • -

      文本编码

      -

      我的读取器知道文件是什么编码,还是在猜?

      -

      text-encoding

      +

      测试框架 EN

      +

      在 pytest、Playwright、Vitest 和 node:test 中使用这些文件。

      +
    • +
    • +

      桌面应用 EN

      +

      逐个界面介绍程序窗口。

    • -

      上传校验

      -

      我的上传表单是否接受该接受的,并拒绝其余的?

      -

      upload-validation

      +

      工具

      +

      处理现有文件的离线工具:检查压缩包能否安全解压,包括 zip slip 和 zip 炸弹,并核对或写出 SHA-256 校验和。

    -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show 会在你构建之前告诉你这个集合的开销,并且在某个数字只是我们的占位值而不是你的限制时直接说明。 -

    -
    -

    退出码是什么意思?

    -

    - 每种结束方式都有自己的代码,机器可读的输出写到标准输出,失败的运行不会在那里打印任何内容。这张表是冻结的约定,改变某个代码的含义需要提升主版本号。 -

    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    代码含义
    0一切正常。
    1工具内部出现意外错误。
    2命令或参数有误。
    3配方无效。
    4该格式无法完成所请求的操作。
    5读取或写入失败。
    6磁盘空间不足。
    7verify 发现了不一致。
    8运行已结束,但并非所有文件都已生成。
    130被 Ctrl+C 中断。
    143被信号终止,CI 超时就是这个样子。
    -
    -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - 被 Ctrl+C 停止的运行仍会留下清单,也绝不会留下写了一半的文件,所以被取消的任务仍可由下一次运行清理。 -

    -

    - 适用于 GitHub Actions 和 GitLab CI 的现成工作流:如何在 CI 流水线中生成测试文件。 -

    +
    +

    这个工具能做什么,按主题

    +
      +
    • +

      格式

      +

      生成器支持的全部文件格式、每种格式可能的最小文件,以及各自接受的设置。全部 32 种都能在对应软件中打开。

      +
    • +
    • +

      预设

      +

      现成的测试文件集,每套回答一个测试问题:上传限制、文件名、编码、表格导入、空文件和上传校验。

      +
    • +
    • +

      损坏文件

      +

      一个故意弄坏、大小精确的文件,附带说明你的系统应拒绝它的清单。用于测试上传校验和解析器。

      +
    • +
    • +

      示例文件

      +

      下载测试用示例文件:每种格式各一个 1 MB 文件,损坏的 PDF、Word 和 Excel 文件,CSV 表格和占位图片,每个都附 SHA-256。

      +
    • +
    • +

      上传测试用例

      +

      文件上传的测试用例:大小限制、空文件和损坏文件、错误的类型、意外的文件名和压缩包,每个用例都附带用来测试它的文件。

      +
    • +
    • +

      CI 中的测试文件

      +

      在流水线中生成测试文件,而不是提交二进制文件:GitHub Actions 工作流、GitLab 作业、让构建失败的退出码,以及 PowerShell 的陷阱。

      +
    • +
    • +

      精确大小

      +

      fsutil、dd、truncate 和 mkfile,每个都在对应系统上实测,以及当测试需要 PDF 或 PNG 时,这样生成的文件为何不行。

      +
    • +
    -
    -

    有桌面窗口吗?

    -

    - 有,它就是在同一个引擎上加了一个窗口,用于不走脚本的测试。它不是缩水版:有测试逐项对比这两种界面,只有其中一方能做的事必须被声明并说明理由,而不是悄悄地渐行渐远。 -

    +
    +

    还是没解决?

    - 界面有单批生成、预设、同时多批和关于。它会在写入任何内容之前显示一次运行的开销,运行时报告进度,并且可以在中途取消而不会留下写了一半的文件。它目前还不能打开配方文件,配方暂时只属于命令行,窗口通过表单来构建批次。 + tfg <command> --help 会在终端里显示一个命令接收什么。每次拒绝都会说明涉及哪个设置、原因,以及一个可用的值。如果某个功能的表现与页面所说的不同,请告诉我们。那是页面或程序的错误。

    diff --git a/web/public/zh-hans/tools/index.html b/web/public/zh-hans/tools/index.html index 53c9bb8b..cb2cf88c 100644 --- a/web/public/zh-hans/tools/index.html +++ b/web/public/zh-hans/tools/index.html @@ -151,6 +151,21 @@
    +

    文档

    解压前检查压缩包,并核对校验和

    diff --git a/web/public/zh-hant/docs/index.html b/web/public/zh-hant/docs/index.html index 191982ba..6f7c208e 100644 --- a/web/public/zh-hant/docs/index.html +++ b/web/public/zh-hant/docs/index.html @@ -147,350 +147,93 @@

    文件

    - 工具的全部功能,依人們實際會問的問題來組織。儲存庫中的 README 是完整參考,並且始終與你下載的版本一致。 + 如何安裝 tfg、產生第一批測試檔案,以及程式接收與寫出的一切:每個指令與每個參數、配方的每個鍵、清單的每個欄位、每種格式的每個設定。這些頁面是英文的,因為它們在每次建置網站時都由程式本身產生,所以永遠與你下載的版本一致。

    -
    -

    有哪些指令?

    -

    每個指令只做一件事:

    -
    tfg generate    依配方或參數產生檔案
    -tfg validate    檢查配方,不寫入任何內容
    -tfg verify      對照清單檢查目錄
    -tfg cleanup     刪除清單中列出的檔案
    -tfg recipe fmt  以標準形式列印配方
    -tfg preset      依具名的測試問題建立一組檔案
    -tfg formats     列出此版本支援的格式
    -tfg damage      列出此版本可以刻意破壞檔案的方式
    -tfg tool        處理現有檔案的小工具
    -tfg version     列印工具版本
    -tfg license     列印授權條款及其對產生檔案的意義
    -

    - tfg tool 包含處理現有檔案的工具,例如在解壓縮前檢查壓縮檔。工具說明了其中每一個。 -

    -
    - -
    -

    如何產生一個大小精確的檔案?

    -

    - 指定格式、大小與輸出位置。大小以 1024 進位計算,所以 2mb 是 2097152 位元組。直接寫位元組數也可以,所以 --size - 10485761 要求的就是恰好這麼多。 -

    -
    tfg generate --format png --size 2mb --out ./out
    -

    generate 常用的參數:

    -
    - - - - - - - - - - - - - - - - - -
    參數作用
    --format <id>檔案格式,例如 txt
    --size <size>每個檔案的精確大小,例如 10mb 或直接寫位元組數
    --size-range <a-b>從範圍內為每個檔案抽取一個大小,例如 1kb-8kb。抽取結果來自種子
    --boundary <size>圍繞一個限制的三個檔案:小一位元組、恰好等於限制、大一位元組
    --count <n>產生多少個檔案。預設 1
    --name <template>檔名範本,例如 invoice_{index:04}.txt
    --out <dir>寫入的目錄
    --seed <n>本次執行的種子。相同的種子得到相同的位元組
    --set <k>=<v>一項格式設定,可重複使用
    --damage <name>刻意破壞檔案,可重複使用,並依序套用。執行 tfg damage 查看清單
    --expected <outcome>accept、reject、sanitize 或 unspecified
    --dry-run只統計並顯示,完全不寫入
    --json將清單寫到標準輸出
    -
    -
    - -
    -

    如何做出刻意損壞的檔案?

    -

    - 本工具寫出的其他所有檔案在構造上都是正確的,這回答了上傳驗證器會問的三個問題中的兩個。--damage - 回答第三個,也就是檔案到底能不能開啟。檔案先正常產生,再被破壞,因此仍然維持你要求的大小。 -

    -
    tfg generate --format png --size 2mb --damage zero-head --out ./zero-head
    -tfg generate --format png --size 2mb --damage zero-head:bytes=16 --out ./zero-head-16
    -

    - 設定寫在冒號後面。該參數可以重複,寫入的順序就是套用的順序。tfg damage 會列出此版本能做什麼,以及每種破壞接受哪些設定。 -

    -

    在配方中,這個鍵是一個清單,內容是名稱或設定:

    -
    targets:
    -  - id: broken
    -    format: png
    -    count: 5
    -    size: 2mb
    -    damage:
    -      - zero-head
    -      - type: zero-head
    -        bytes: 16
    -

    - 受損檔案在清單中會得到 expected: reject,並在旁邊記錄所做的破壞。有兩種情況會在寫入任何內容之前被拒絕,因為各自都會在磁碟上留下清單描述有誤的檔案: -

    -
      -
    • 檔案小於破壞所需的大小,因為它會原樣輸出
    • -
    • - 在破壞旁邊寫 expected: accept,因為沒有任何檔案能滿足它。如果受測系統應該修復該檔案,請寫 - sanitize,如果你問的正是這個問題,請寫 unspecified -
    • -
    -

    - 第三種無法事先得知。如果某個破壞執行後沒有改動任何位元組,該檔案會被捨棄而不是寫出,執行會繼續,指出是哪個檔案,並以部分完成的結束碼收尾。 -

    -

    - 一步一步來,附帶一個讀取清單的測試:如何製作用於測試的損毀檔案。 -

    -
    - -
    -

    配方長什麼樣子?

    -

    - 配方是一個描述整次執行的 YAML 檔案。把它與測試放在一起提交,fixture 就不再是儲存庫裡的二進位檔,任何人都可以用一個只有幾百個字元的檔案逐位元組重建它們。 -

    -
    # fixtures.yaml
    -version: 1
    -seed: 7741
    -
    -defaults:
    -  label: true
    -
    -targets:
    -  - id: invoices
    -    format: pdf
    -    count: 25
    -    size: 300kb
    -    name: invoice_{index:04}.pdf
    -    properties:
    -      pages: 3
    -      page_size: a4
    -    expected: accept
    -
    -  - id: over_the_limit
    -    format: png
    -    count: 2
    -    size: 12mb
    -    expected:
    -      outcome: reject
    -      reason: size_limit
    -
    -  - id: bundle
    -    format: zip
    -    contains:
    -      - format: txt
    -        count: 200
    -        size: 4kb
    -
    -output:
    -  dir: ./fixtures
    -  manifest: manifest.json
    -
    tfg validate fixtures.yaml
    -tfg generate fixtures.yaml
    -

    - 每個 target 必須恰好有 size、size-range、boundary 或 - contains - 其中一個。兩個是錯誤,一個都沒有也是錯誤。無效的配方不會寫入任何檔案,並且會一次回報所有問題,而不是只報第一個,每個問題都會指明所涉及的設定。 -

    -
    - -
    -

    如何宣告我的系統應如何處理某個檔案?

    -

    只需結果時用簡短寫法,原因重要時用完整寫法:

    -
    expected: accept
    -
    expected:
    -  outcome: reject
    -  reason: size_limit
    -

    - 結果有 accept、reject、sanitize 與 - unspecified。原因是封閉清單,方便報告依原因分組:content_malformed、count_limit、dimensions_limit、duplicate、encoding_invalid、extension_rule、filename_invalid、filename_too_long、filename_traversal、malware_signature、mime_mismatch、nesting_depth、none、size_limit - 與 size_zero。 -

    -

    - 原因指明的是起作用的規則,而不是裁決。所以同一個原因可以出現在兩種結果之下:比限制小一位元組的檔案是 accept,而它所涉及的規則仍然是 - size_limit。 -

    -
    - -
    -

    清單裡有什麼?

    -

    - 每次執行結束時,包括被中斷的執行,它都會寫在檔案旁邊。每個檔案一項: -

    -
    {
    -  "manifest_version": "1.0",
    -  "tool": { "name": "testing-files-generator", "version": "0.6.0-rc1" },
    -  "run": {
    -    "id": "run_b359aa8d94",
    -    "seed": 0,
    -    "command": "tfg generate --format png --size 2mb --out ./out",
    -    "platform": { "os": "windows", "arch": "amd64" },
    -    "complete": true
    -  },
    -  "summary": {
    -    "file_count": 1,
    -    "total_bytes": 2097152,
    -    "by_format": { "png": 1 },
    -    "by_expected": { "unspecified": 1 }
    -  },
    -  "files": [
    -    {
    -      "path": "files_0001.png",
    -      "bytes": 2097152,
    -      "format": "png",
    -      "fidelity": "full",
    -      "determinism": "byte",
    -      "seed": "8dc2d18c",
    -      "hashes": { "sha256": "1a1f7c..." },
    -      "properties": { "width": 640, "height": 480 },
    -      "expected": {
    -        "outcome": "unspecified",
    -        "detail": "No expectation was declared for this file.",
    -        "confidence": "policy_dependent"
    -      }
    -    }
    -  ]
    -}
    -

    - 執行來自配方時會加上 recipe_hash,來自預設集時會加上 preset 與 - overrides,因此清單總能追溯到產生它的來源。 -

    -

    - 每一項還帶有 target_id,也就是配方中產生該檔案的 target 的 id,summary.by_target 則統計每個 target - 產生的檔案數。因此有多個 target 的配方可以逐個 target 檢查,無需閱讀檔名。 -

    -
    - -
    -

    什麼是預設集?

    -

    - 預設集是回答常見測試問題的現成檔案組,你不必自己設計。預設集底層就是普通配方,eject - 會把配方列印出來,供你從那裡開始編輯。每個預設集都有自己的頁面,說明它通常能發現什麼、組合裡有什麼,以及它接受的每項設定。 -

    +
    +

    文件頁面

    • -

      空檔案與最小檔案

      -

      一個合法且達到格式允許最小大小的檔案能通過嗎?

      -

      empty-and-minimal

      +

      安裝 EN

      +

      下載適用於 Windows、macOS 或 Linux 的版本並驗證壓縮檔,或透過 Docker、npm、pip、Go 安裝。

    • -
    • -

      檔名處理

      -

      我的系統能否正確儲存、顯示並傳回它沒料到的檔名?

      -

      filename-handling

      +
    • +

      入門 EN

      +

      先產生一個精確大小的檔案,再產生一萬個,驗證、刪除,並寫成配方。

    • -
    • -

      圖片尺寸

      -

      我的系統能接受螢幕和平台所用尺寸的圖片嗎?

      -

      picture-sizes

      +
    • +

      指令 EN

      +

      每個指令與每個參數及其預設值,以及所有結束碼。

      +
    • +
    • +

      撰寫配方 EN

      +

      配方的每個鍵、大小、檔名、預期反應、損壞、壓縮檔與預設集。

    • -

      大小邊界

      -

      大小限制是否恰好在宣告的位置生效?

      -

      size-boundaries

      +

      配方集 EN

      +

      可直接下載的配方,用於上傳、匯入、壓縮檔、電子郵件、媒體、CI 與大量檔案。

      +
    • +
    • +

      清單 EN

      +

      manifest.json 的每個欄位,以及測試如何讀取它。

    • -

      表格匯入

      -

      我的表格匯入能應付真實工具匯出的內容嗎?

      -

      tabular-import

      +

      格式設定 EN

      +

      每種格式的每個設定,包括可接受的值與預設值。

    • -

      文字編碼

      -

      我的讀取器知道檔案是什麼編碼,還是在猜?

      -

      text-encoding

      +

      測試框架 EN

      +

      在 pytest、Playwright、Vitest 與 node:test 中使用這些檔案。

      +
    • +
    • +

      桌面應用程式 EN

      +

      逐一介紹程式視窗的每個畫面。

    • -

      上傳驗證

      -

      我的上傳表單是否接受該接受的,並拒絕其餘的?

      -

      upload-validation

      +

      工具

      +

      處理現有檔案的離線工具:檢查壓縮檔能否安全解壓縮,包括 zip slip 與 zip 炸彈,並核對或寫出 SHA-256 總和檢查碼。

    -
    tfg preset list
    -tfg preset show size-boundaries
    -tfg generate --preset size-boundaries --limit 10mb --out ./edges
    -tfg preset eject size-boundaries > my.yaml
    -

    - show 會在你建置之前告訴你這個組合的開銷,並且在某個數字只是我們的預留值而不是你的限制時直接說明。 -

    -
    -

    結束碼是什麼意思?

    -

    - 每種結束方式都有自己的代碼,機器可讀的輸出寫到標準輸出,失敗的執行不會在那裡列印任何內容。這張表是凍結的約定,改變某個代碼的意義需要提升主版本號。 -

    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    代碼意義
    0一切正常。
    1工具內部發生非預期的錯誤。
    2指令或參數有誤。
    3配方無效。
    4該格式無法完成所要求的操作。
    5讀取或寫入失敗。
    6磁碟空間不足。
    7verify 發現不一致。
    8執行已結束,但並非所有檔案都已產生。
    130被 Ctrl+C 中斷。
    143被訊號終止,CI 逾時就是這個樣子。
    -
    -
    - name: build the fixtures
    -  run: tfg generate fixtures.yaml --out ./fixtures
    -
    -- name: run the tests
    -  run: pytest tests/
    -
    -- name: nothing moved
    -  run: tfg verify ./fixtures/manifest.json
    -

    - 被 Ctrl+C 停止的執行仍會留下清單,也絕不會留下寫了一半的檔案,所以被取消的工作仍可由下一次執行清理。 -

    -

    - 適用於 GitHub Actions 和 GitLab CI 的現成工作流程:如何在 CI 流程中產生測試檔案。 -

    +
    +

    這個工具能做什麼,依主題

    +
      +
    • +

      格式

      +

      產生器支援的所有檔案格式、每種格式可能的最小檔案,以及各自接受的設定。全部 32 種都能在對應軟體中開啟。

      +
    • +
    • +

      預設集

      +

      現成的測試檔案組,每組回答一個測試問題:上傳限制、檔名、編碼、表格匯入、空檔案與上傳驗證。

      +
    • +
    • +

      損毀檔案

      +

      一個刻意弄壞、大小精確的檔案,附帶說明你的系統應拒絕它的清單。用於測試上傳驗證和剖析器。

      +
    • +
    • +

      範例檔案

      +

      下載測試用範例檔案:每種格式各一個 1 MB 檔案,損毀的 PDF、Word 與 Excel 檔案,CSV 表格和佔位圖片,每個都附 SHA-256。

      +
    • +
    • +

      上傳測試案例

      +

      檔案上傳的測試案例:大小限制、空檔案與損毀檔案、錯誤的類型、意料之外的檔名和壓縮檔,每個案例都附上用來測試它的檔案。

      +
    • +
    • +

      CI 中的測試檔案

      +

      在流程中產生測試檔案,而不是提交二進位檔案:GitHub Actions 工作流程、GitLab 作業、讓建置失敗的結束碼,以及 PowerShell 的陷阱。

      +
    • +
    • +

      精確大小

      +

      fsutil、dd、truncate 與 mkfile,各自在對應系統上實測,以及當測試需要 PDF 或 PNG 時,這樣產生的檔案為何不行。

      +
    • +
    -
    -

    有桌面視窗嗎?

    -

    - 有,它就是在同一個引擎上加了一個視窗,用於不走腳本的測試。它不是縮水版:有測試逐項比對這兩種介面,只有其中一方能做的事必須被宣告並說明理由,而不是悄悄地漸行漸遠。 -

    +
    +

    還是沒有解決?

    - 畫面有單批產生、預設集、同時多批與關於。它會在寫入任何內容之前顯示一次執行的開銷,執行時回報進度,並且可以在中途取消而不會留下寫了一半的檔案。它目前還不能開啟配方檔,配方暫時只屬於命令列,視窗透過表單來建立批次。 + tfg <command> --help 會在終端機中顯示一個指令接收什麼。每次拒絕都會說明涉及哪個設定、原因,以及一個可用的值。如果某個功能的表現與頁面所說的不同,請告訴我們。那是頁面或程式的錯誤。

    diff --git a/web/public/zh-hant/tools/index.html b/web/public/zh-hant/tools/index.html index 3f48caf8..b94c97b4 100644 --- a/web/public/zh-hant/tools/index.html +++ b/web/public/zh-hant/tools/index.html @@ -151,6 +151,21 @@
    +

    文件

    解壓縮前檢查壓縮檔,並核對總和檢查碼

    diff --git a/web/recipes/archive-upload.yaml b/web/recipes/archive-upload.yaml new file mode 100644 index 00000000..cb926596 --- /dev/null +++ b/web/recipes/archive-upload.yaml @@ -0,0 +1,113 @@ +# Archives for testing an upload or an import that unpacks what it is given. +# +# tfg generate archive-upload.yaml +# +# The files and manifest.json land in ./archive-upload. Every entry inside an +# archive is a real file of its format. Run "tfg tool archive-scan" on any of +# them to see what is inside without unpacking it. + +version: 1 +seed: 404 + +targets: + # Ordinary archives: text files and PDF files in a ZIP, and pictures in a + # TAR.GZ, which a form that takes ZIP files may or may not take as well. + - id: texts_zip + format: zip + size: 200kb + name: texts.zip + properties: + entries: 20 + entry_format: txt + entry_size: 8kb + expected: accept + - id: documents_zip + format: zip + size: 2mb + name: documents.zip + properties: + entries: 5 + entry_format: pdf + entry_size: 300kb + compression: default + expected: accept + - id: pictures_targz + format: targz + size: 2mb + name: pictures.tar.gz + properties: + entries: 10 + entry_format: png + entry_size: 100kb + expected: + outcome: unspecified + reason: extension_rule + + # Shapes an unpacker meets less often: many entries, files five folders + # deep, folders listed as entries of their own, and an archive with nothing + # in it. + - id: many_entries + format: zip + size: 20mb + name: many_entries.zip + properties: + entries: 5000 + entry_format: txt + entry_size: 1kb + expected: + outcome: unspecified + reason: count_limit + - id: nested + format: zip + size: 200kb + name: five_folders_deep.zip + properties: + depth: 5 + expected: + outcome: unspecified + reason: nesting_depth + - id: with_folders + format: zip + size: 100kb + name: with_folders.zip + properties: + entries: 4 + depth: 2 + directory_entries: true + expected: accept + # Kept at 1 KB. A larger empty archive needs a filler entry to reach its + # size, and would no longer be empty. + - id: empty_zip + format: zip + size: 1kb + name: empty.zip + properties: + entries: 0 + expected: + outcome: unspecified + reason: count_limit + + # An archive locked with a password, which an unpacker cannot read without + # being given it. The password is test. + - id: encrypted + format: zip + size: 100kb + name: encrypted.zip + properties: + encryption: aes-256 + password: test + expected: unspecified + + # Broken on purpose: a ZIP cut short the way an interrupted upload leaves it. + - id: truncated_zip + format: zip + size: 500kb + name: truncated.zip + damage: + - truncate + expected: + outcome: reject + reason: content_malformed + +output: + dir: ./archive-upload diff --git a/web/recipes/bulk-files.yaml b/web/recipes/bulk-files.yaml new file mode 100644 index 00000000..e1683edf --- /dev/null +++ b/web/recipes/bulk-files.yaml @@ -0,0 +1,22 @@ +# Ten thousand small files, for testing what a system does with many files at +# once: a sync folder, a backup, a file browser, a search index, a batch job. +# +# tfg generate bulk-files.yaml +# +# The files and manifest.json land in ./bulk-files, about 45 MB in all. The +# sizes are drawn from the seed, so the same recipe gives the same set every +# time. Raise the count for a larger set. + +version: 1 +seed: 606 + +targets: + - id: logs + format: log + count: 10000 + size-range: 1kb-8kb + name: log_{index:04}.log + expected: accept + +output: + dir: ./bulk-files diff --git a/web/recipes/ci-smoke.yaml b/web/recipes/ci-smoke.yaml new file mode 100644 index 00000000..cc8ea166 --- /dev/null +++ b/web/recipes/ci-smoke.yaml @@ -0,0 +1,71 @@ +# One small file of each common format, for a quick check in CI that a system +# reads what it should. Runs in a second and writes well under a megabyte. +# +# tfg generate ci-smoke.yaml +# tfg verify ci-smoke/manifest.json +# +# The files and manifest.json land in ./ci-smoke. The same seed gives the same +# bytes on every machine, so the set never has to be committed. + +version: 1 +seed: 505 + +targets: + - id: txt + format: txt + size: 4kb + name: smoke.txt + expected: accept + - id: csv + format: csv + size: 8kb + name: smoke.csv + expected: accept + - id: json + format: json + size: 8kb + name: smoke.json + expected: accept + - id: xml + format: xml + size: 8kb + name: smoke.xml + expected: accept + - id: html + format: html + size: 8kb + name: smoke.html + expected: accept + - id: pdf + format: pdf + size: 16kb + name: smoke.pdf + expected: accept + - id: docx + format: docx + size: 16kb + name: smoke.docx + expected: accept + - id: xlsx + format: xlsx + size: 16kb + name: smoke.xlsx + expected: accept + - id: png + format: png + size: 16kb + name: smoke.png + expected: accept + - id: jpg + format: jpg + size: 16kb + name: smoke.jpg + expected: accept + - id: zip + format: zip + size: 16kb + name: smoke.zip + expected: accept + +output: + dir: ./ci-smoke diff --git a/web/recipes/document-upload.yaml b/web/recipes/document-upload.yaml new file mode 100644 index 00000000..d40aecfb --- /dev/null +++ b/web/recipes/document-upload.yaml @@ -0,0 +1,126 @@ +# Documents for testing a document upload: invoices, CVs, reports, contracts. +# +# tfg generate document-upload.yaml +# +# The files and manifest.json land in ./document-upload. The manifest says +# which files your form should take and which it should turn away. Change the +# limit below to the one your form declares before you run it. + +version: 1 +seed: 202 + +# Seven PDF files around the size limit, from 1 MB under it to 1 MB over, with +# the limit itself among them. They come from the size-boundaries preset. +extends: preset:size-boundaries +with: + limit: 10mb + format: pdf + +targets: + # PDF and Word, which a document form takes, then Excel, PowerPoint, RTF + # and plain text, which some forms refuse. Whether yours does is its + # policy, so those say unspecified: set them to what your form does. + - id: invoice_pdf + format: pdf + size: 300kb + name: invoice.pdf + properties: + pages: 3 + page_size: a4 + expected: accept + - id: letter_pdf + format: pdf + size: 200kb + name: letter_size.pdf + properties: + pages: 2 + page_size: letter + expected: accept + - id: cv_docx + format: docx + size: 200kb + name: cv.docx + properties: + paragraphs: 40 + expected: accept + - id: report_xlsx + format: xlsx + size: 1mb + name: report.xlsx + properties: + rows: 500 + columns: 12 + expected: + outcome: unspecified + reason: extension_rule + - id: slides_pptx + format: pptx + size: 1mb + name: slides.pptx + expected: + outcome: unspecified + reason: extension_rule + - id: notes_rtf + format: rtf + size: 50kb + name: notes.rtf + expected: + outcome: unspecified + reason: extension_rule + - id: notes_txt + format: txt + size: 20kb + name: notes.txt + expected: + outcome: unspecified + reason: extension_rule + + # A long document: 500 pages in one PDF. + - id: long_pdf + format: pdf + size: 5mb + name: long_document.pdf + properties: + pages: 500 + expected: accept + + # Broken documents: a PDF with its first bytes zeroed, and a Word file cut in + # half the way an interrupted upload leaves it. + - id: corrupt_pdf + format: pdf + size: 300kb + name: corrupt.pdf + damage: + - zero-head + expected: + outcome: reject + reason: content_malformed + - id: truncated_docx + format: docx + size: 300kb + name: truncated.docx + damage: + - truncate + expected: + outcome: reject + reason: content_malformed + + # Files that are not what their names say: a spreadsheet named as a PDF, and + # an empty file with a PDF's name. + - id: xlsx_named_pdf + format: xlsx + size: 100kb + name: not_a_document.pdf + expected: + outcome: reject + reason: mime_mismatch + - id: empty_pdf + format: txt + size: 0 + name: empty.pdf + expected: + outcome: reject + reason: size_zero + +output: + dir: ./document-upload diff --git a/web/recipes/email-attachments.yaml b/web/recipes/email-attachments.yaml new file mode 100644 index 00000000..e859d7b4 --- /dev/null +++ b/web/recipes/email-attachments.yaml @@ -0,0 +1,123 @@ +# Email messages for testing a system that reads mail: a support inbox, a mail +# import, an archive, an attachment scanner. +# +# tfg generate email-attachments.yaml +# +# The files and manifest.json land in ./email-attachments. Each .eml file opens +# in a mail program, and every attachment inside it is a real file of its +# format. + +version: 1 +seed: 707 + +targets: + # Plain messages, and one written in HTML with a plain text part beside it. + - id: plain + format: eml + size: 8kb + name: plain.eml + expected: accept + - id: html + format: eml + size: 32kb + name: html_and_text.eml + properties: + body: alternative + expected: accept + + # Attachments: a PDF, several pictures, and one large file. + - id: pdf_attached + format: eml + size: 500kb + name: invoice_attached.eml + properties: + attachments: 1 + attachment_format: pdf + attachment_size: 300kb + expected: accept + - id: pictures_attached + format: eml + size: 1mb + name: five_pictures.eml + properties: + attachments: 5 + attachment_format: jpg + attachment_size: 100kb + expected: accept + - id: large_attachment + format: eml + size: 15mb + name: large_attachment.eml + properties: + attachments: 1 + attachment_format: zip + attachment_size: 10mb + expected: + outcome: unspecified + reason: size_limit + + # A picture shown inside the message rather than attached to it. + - id: inline_picture + format: eml + size: 100kb + name: inline_picture.eml + properties: + body: html + inline: 1 + inline_format: png + inline_size: 40kb + expected: accept + + # Encodings a reader has to get right: quoted-printable and base64 text, a + # message in windows-1250, and headers with words outside ASCII. + - id: quoted_printable + format: eml + size: 16kb + name: quoted_printable.eml + properties: + text_encoding: quoted-printable + charset: utf-8 + expected: accept + - id: base64 + format: eml + size: 16kb + name: base64.eml + properties: + text_encoding: base64 + charset: utf-8 + expected: accept + - id: windows_1250 + format: eml + size: 16kb + name: windows_1250.eml + properties: + text_encoding: 8bit + charset: windows-1250 + expected: accept + - id: encoded_headers + format: eml + size: 16kb + name: encoded_headers.eml + properties: + headers: encoded + expected: accept + + # Unusual shapes: a message sent to a thousand people, and a message + # forwarded inside a message, three deep. + - id: many_recipients + format: eml + size: 100kb + name: thousand_recipients.eml + properties: + recipients: 1000 + expected: accept + - id: forwarded + format: eml + size: 32kb + name: forwarded_3_deep.eml + properties: + message_depth: 3 + expected: accept + +output: + dir: ./email-attachments diff --git a/web/recipes/image-upload.yaml b/web/recipes/image-upload.yaml new file mode 100644 index 00000000..f1f77ddd --- /dev/null +++ b/web/recipes/image-upload.yaml @@ -0,0 +1,122 @@ +# Pictures for testing an image upload: a profile photo, an avatar, a gallery. +# +# tfg generate image-upload.yaml +# +# The files and manifest.json land in ./image-upload. The manifest says which +# files your form should take and which it should turn away. Change the limit +# below to the one your form declares before you run it. + +version: 1 +seed: 101 + +# Seven pictures around the size limit, from 1 MB under it to 1 MB over, with +# the limit itself among them. They come from the size-boundaries preset. +extends: preset:size-boundaries +with: + limit: 5mb + format: jpg + +targets: + # JPEG and PNG, which an image form takes, and WebP and GIF, which some + # forms refuse. Whether yours does is its policy, so those two say + # unspecified: set them to what your form does. + - id: photo_jpg + format: jpg + size: 500kb + name: photo.jpg + expected: accept + - id: screenshot_png + format: png + size: 500kb + name: screenshot.png + expected: accept + - id: picture_webp + format: webp + size: 500kb + name: picture.webp + expected: + outcome: unspecified + reason: extension_rule + - id: picture_gif + format: gif + size: 200kb + name: picture.gif + expected: + outcome: unspecified + reason: extension_rule + + # The sizes in pixels a form may refuse: one pixel, and a picture of 36 + # megapixels. Whether either is welcome is your form's decision. + - id: one_pixel + format: png + size: smallest + name: one_pixel.png + properties: + width: 1 + height: 1 + expected: + outcome: unspecified + reason: dimensions_limit + - id: huge_picture + format: jpg + size: smallest + name: huge_picture.jpg + properties: + width: 6000 + height: 6000 + expected: + outcome: unspecified + reason: dimensions_limit + + # Broken pictures at an ordinary size: the first bytes zeroed, and a PNG + # cut in half the way an interrupted upload leaves it. + - id: corrupt_jpg + format: jpg + size: 300kb + name: corrupt.jpg + damage: + - zero-head + expected: + outcome: reject + reason: content_malformed + - id: truncated_png + format: png + size: 300kb + name: truncated.png + damage: + - truncate + expected: + outcome: reject + reason: content_malformed + + # Files that are not pictures: a PDF with a picture's name, and an empty + # file named like a photo. + - id: pdf_named_jpg + format: pdf + size: 100kb + name: not_a_photo.jpg + expected: + outcome: reject + reason: mime_mismatch + - id: empty_jpg + format: txt + size: 0 + name: empty.jpg + expected: + outcome: reject + reason: size_zero + + # A real picture to upload under a name that climbs out of the upload + # folder. It is written as climbs_out.jpg, and the manifest gives the name + # to send it under in send_as. + - id: climbs_out + format: jpg + size: 100kb + name: climbs_out.jpg + send-as: ../../climbs_out.jpg + expected: + outcome: reject + reason: filename_traversal + +output: + dir: ./image-upload diff --git a/web/recipes/media-upload.yaml b/web/recipes/media-upload.yaml new file mode 100644 index 00000000..085cc531 --- /dev/null +++ b/web/recipes/media-upload.yaml @@ -0,0 +1,98 @@ +# Video and sound for testing a media upload: a video message, a voice note, a +# course platform, a transcoding queue. +# +# tfg generate media-upload.yaml +# +# The files and manifest.json land in ./media-upload. Every file plays in an +# ordinary player. Change the limit below to the one your form declares before +# you run it. + +version: 1 +seed: 808 + +# Seven videos around the size limit, from 1 MB under it to 1 MB over, with the +# limit itself among them. They come from the size-boundaries preset. +extends: preset:size-boundaries +with: + limit: 10mb + format: mp4 + +targets: + # MP4, which a video form takes, then WebM and a WAV voice note, which + # some forms refuse. Whether yours does is its policy, so those two say + # unspecified: set them to what your form does. + - id: video_mp4 + format: mp4 + size: 2mb + name: video.mp4 + properties: + width: 1280 + height: 720 + duration: 5s + expected: accept + - id: video_webm + format: webm + size: 2mb + name: video.webm + properties: + width: 1280 + height: 720 + duration: 5s + expected: + outcome: unspecified + reason: extension_rule + - id: voice_wav + format: wav + size: 1mb + name: voice_note.wav + properties: + sample_rate: 16000 + channels: 1 + expected: + outcome: unspecified + reason: extension_rule + + # Shapes a player or a transcoder meets less often: a portrait phone video, + # ten minutes of video at one frame a second, and sound that is only + # silence. Whether ten minutes is too long is your platform's decision. + - id: portrait + format: mp4 + size: 2mb + name: portrait_phone.mp4 + properties: + width: 720 + height: 1280 + duration: 5s + expected: accept + - id: long_video + format: mp4 + size: 6mb + name: ten_minutes.mp4 + properties: + width: 320 + height: 240 + duration: 10m + frame_rate: 1 + expected: unspecified + - id: silence + format: wav + size: 500kb + name: silence.wav + properties: + content: silence + expected: unspecified + + # Broken on purpose: a video cut short the way an interrupted upload leaves + # it. + - id: truncated_mp4 + format: mp4 + size: 2mb + name: truncated.mp4 + damage: + - truncate + expected: + outcome: reject + reason: content_malformed + +output: + dir: ./media-upload diff --git a/web/recipes/spreadsheet-import.yaml b/web/recipes/spreadsheet-import.yaml new file mode 100644 index 00000000..a2c5afe1 --- /dev/null +++ b/web/recipes/spreadsheet-import.yaml @@ -0,0 +1,130 @@ +# Tables for testing an import: a CSV or Excel upload, a bulk import screen, a +# data pipeline that reads files. +# +# tfg generate spreadsheet-import.yaml +# +# The files and manifest.json land in ./spreadsheet-import. Every file here is +# a well formed table. The ones marked accept are what most tools export, and +# an importer should take them. The others are shapes and sizes an importer may +# refuse on purpose, so they say unspecified: set them to what your importer +# does. The two at the end are broken on purpose. + +version: 1 +seed: 303 + +targets: + # The same table written the ways real tools export it. + - id: comma_lf + format: csv + size: 50kb + name: comma_lf.csv + expected: accept + - id: comma_crlf + format: csv + size: 50kb + name: comma_crlf.csv + properties: + line_ending: crlf + expected: accept + - id: semicolon + format: csv + size: 50kb + name: semicolon.csv + properties: + delimiter: semicolon + expected: + outcome: unspecified + reason: none + - id: tab + format: csv + size: 50kb + name: tab_separated.csv + properties: + delimiter: tab + expected: + outcome: unspecified + reason: none + - id: no_header + format: csv + size: 50kb + name: no_header.csv + properties: + header: false + expected: + outcome: unspecified + reason: none + - id: every_field_quoted + format: csv + size: 50kb + name: every_field_quoted.csv + properties: + quote_style: all + expected: accept + + # Shapes an importer meets less often: a wide table and a large one. + - id: wide + format: csv + size: 500kb + name: wide_200_columns.csv + properties: + columns: 200 + expected: + outcome: unspecified + reason: count_limit + - id: large + format: csv + size: 20mb + name: large.csv + expected: + outcome: unspecified + reason: size_limit + + # Excel files: a small sheet, a long one and a single cell. + - id: sheet + format: xlsx + size: 2mb + name: sheet.xlsx + properties: + rows: 1000 + columns: 10 + expected: accept + - id: long_sheet + format: xlsx + size: 12mb + name: long_sheet.xlsx + properties: + rows: 10000 + columns: 6 + expected: + outcome: unspecified + reason: count_limit + - id: one_cell + format: xlsx + size: 8kb + name: one_cell.xlsx + properties: + rows: 1 + columns: 1 + expected: accept + + # Broken on purpose: an Excel file cut short, and an empty file named as a + # CSV. + - id: truncated_xlsx + format: xlsx + size: 200kb + name: truncated.xlsx + damage: + - truncate + expected: + outcome: reject + reason: content_malformed + - id: empty_csv + format: txt + size: 0 + name: empty.csv + expected: + outcome: reject + reason: size_zero + +output: + dir: ./spreadsheet-import diff --git a/web/templates/layout.html b/web/templates/layout.html index c6f7f447..a10a7f0a 100644 --- a/web/templates/layout.html +++ b/web/templates/layout.html @@ -20,9 +20,9 @@ -{{- range .Switches }} +{{- range .Switches }}{{ if not .Elsewhere }} -{{- end }} +{{- end }}{{ end }} @@ -63,7 +63,7 @@

    @@ -72,6 +72,9 @@
    +{{- if and .Docs .Up }} +{{ template "docsMenu" . }} +{{- end }} {{ .Body }}
    diff --git a/web/templates/partials.html b/web/templates/partials.html index a6e0fdc1..e45b3eda 100644 --- a/web/templates/partials.html +++ b/web/templates/partials.html @@ -288,6 +288,31 @@ {{ end }}tfg {{ $c.Name }}{{ $c.Pad }}{{ $c.Summary }}{{ end }} {{- end -}} +{{- define "docsMenu" -}} + +{{- end -}} + +{{- define "linkCards" -}} +
      +{{- range . }} +
    • + {{- range $i, $a := .Anchors }}{{ if $i }}{{ end }}{{ end }} +

      {{ .Title }}{{ if .English }} EN{{ end }}

      +

      {{ .Text }}

      +
    • +{{- end }} +
    +{{- end -}} + {{- define "downloadCta" -}}