improve fragment extraction from derivations

- only extract fragments from derivations after collecting all parse
  trees, to avoid redundant work
- fix typo which caused a TypeError
- when a test from tests/run.sh fails, dump its output