I would like to be able to generate random bytea fields of arbitrary length (<1Gb) for populating test data.

What is the best way of doing this?
Enhancing Jack Douglas's answer to avoid the need for PL/PgSQL looping and bytea concatenation, you can use:

CREATE OR REPLACE FUNCTION random_bytea(bytea_length integer)
RETURNS bytea AS $body$
SELECT decode(string_agg(lpad(to_hex(width_bucket(random(), 0, 1, 256)-1),2,'0') ,''), 'hex')
FROM generate_series(1, $1);$body\$
LANGUAGE 'sql'
VOLATILE
SET search_path = 'pg_catalog';

It's a simple SQL function that's cheaper to call than PL/PgSQL.

The difference in performance due to the changed aggregation method is immense for larger bytea values. Though the original function is actually up to 3x faster for sizes < 50 bytes, this one scales much better for larger values.

**Or use a C extension function**:

I've implemented a random bytea generator as a simple C extension function. It's in my [scrapcode repository on GitHub](https://github.com/ringerc/scrapcode/tree/master/postgresql/random_bytea). See the README there.

It nukes the performance of the above SQL version:

none
regress=# \a
regress=# \o /dev/null
regress=# \timing on
regress=# select random_bytea(2000000);
Time: 895.972 ms
regress=# drop function random_bytea(integer);
regress=# create extension random_bytea;
regress=# select random_bytea(2000000);
Time: 24.126 ms

> I would like to be able to generate random bytea fields of arbitrary length

This function will do it, but 1Gb will take a long time because it does not scale linearly with output length:

<>http://dbfiddle.uk/?rdbms=postgres_9.6&fiddle=7b55d9b493c5930cdc1c601304ca738d
{"ft_lang_label":"__label__en","ft_lang_prob":0.6759966,"math_prob":0.79672945,"size":1669,"snap":"2020-45-2020-50","text_gpt3_token_len":429,"char_repetition_ratio":0.12972973,"word_repetition_ratio":0.044843048,"special_character_ratio":0.2684242,"punctuation_ratio":0.13175675,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9567409,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2020-11-29T07:54:46Z\",\"WARC-Record-ID\":\"<urn:uuid:83ef10e2-bfbe-406e-afec-a5ea2696370c>\",\"Content-Length\":\"25336\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:c5594efc-2579-4dd6-9b4d-accbb26e20ef>\",\"WARC-Concurrent-To\":\"<urn:uuid:faeeea0b-0dee-4f03-99bc-6bef8bfd6c15>\",\"WARC-IP-Address\":\"195.200.211.87\",\"WARC-Target-URI\":\"https://topanswers.xyz/databases?q=146\",\"WARC-Payload-Digest\":\"sha1:JLNTHQL4Q7XNHK6XZFZBVCDXY5GNRXRU\",\"WARC-Block-Digest\":\"sha1:W5H7JYDHJARJ5GST6ZPMIXEOKC3LSKEY\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2020/CC-MAIN-2020-50/CC-MAIN-2020-50_segments_1606141197278.54_warc_CC-MAIN-20201129063812-20201129093812-00716.warc.gz\"}"}